Trì hoãn được tạo để thực thi mã sau phản hồi của một số lệnh gọi từ xa (ví dụ: ajax).
vì vậy bạn có thể có:
load_conf = function (user_id) {
var def = $.Deferred()
$("http://get_conf_data_url?user_id="+user_id).done(function (data) {
var processed_conf = do_something_with(data);
def.resolve(processed_conf);
})
return def.promise();
}
vì vậy bạn có thể đi:
load_conf(1).done(function (processed_data) {
do_something_with(processed_data);
});
gì về thực hiện một số mã sau khi tải exacly 3 cấu hình? Bạn có thể làm một cái gì đó như:
$.when(load_conf(1), load_conf(2), load_conf(3)).done(function (c1, c2 ,c3) {
console.log("configurations: ", c1, c2, c3);
})
Nhưng những gì về thực hiện một số mã sau khi tải cấu hình N trong đó N là biến? Đối với trường hợp này, bạn có thể sử dụng phương thức Function.prptotype.apply. Bạn có thể chuyển làm đối số đầu tiên một đối tượng sẽ được coi là "this" bên trong hàm. Đối số thứ hai là danh sách các tham số nhưng bên trong một mảng.
vì vậy bạn có thể đi như thế này:
var defs = [];
for (var i=1; i<=N; i++) {
defs.push(load_conf(i));
}
// here's the magic
$.when($,defs).done(function() {
console.log("All conf loaded: ", arguments);
// arguments contains N processed answers
});
Nguồn
2014-03-14 21:46:23
Xem [MDN: 'fun.apply()'] (https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/ áp dụng) & [JavaScript thông dụng] (http://eloquentjavascript.net/chapter6.html#key5) – gnarf
+1 cho $ .when.apply (null, phương thức) – marverix