i have two javascript functions, save()
and saveAll()
, set up as below:
我有两个javascript函数,save()和saveAll(),设置如下:
function save(data) {
return $.post('/save', data);
}
function saveAll(callback) {
var dataArray = [];
$.each(dataArray, function() {
save(this);
});
callback();
}
i'm interested in modifying saveAll()
so that it leverages jquery deferred objects, and raises the callback
function once all save()
operations have completed. however, i'm unsure of the exact syntax... specifically with relation to the $.each() inside of the $.when(). would it be something like this?
我有兴趣修改saveAll(),以便它利用jquery延迟对象,并在所有save()操作完成后引发回调函数。但是,我不确定确切的语法...特别是与$ .when()内部的$ .each()有关。会是这样的吗?
function saveAll(callback) {
var dataArray = [];
$.when(
$.each(dataArray, function() {
return save(this);
})
).then(callback);
}
3 个解决方案
#1
21
as Eli pointed out, $.when() accepts a comma separated list of arguments and not an array. using Function.apply()
to pass in the array seems to do the trick.
正如Eli指出的那样,$ .when()接受逗号分隔的参数列表而不是数组。使用Function.apply()传入数组似乎可以解决问题。
function saveAll(callback) {
var dataArray = [], deferreds = [];
$.each(dataArray, function() {
deferreds.push( save() );
});
$.when.apply(window, deferreds).then(callback);
}
#2
1
You should be able to pass a comma-separated list of deferred objects to $.when
and .then
will execute once they all have resolved.
您应该能够将逗号分隔的延迟对象列表传递给$ .when和.then将在它们全部解析后执行。
http://api.jquery.com/jQuery.when/
http://api.jquery.com/jQuery.when/
#3
1
The problem I think is that $.each
is returning your dataArray
, not a list of Deferred
objects like you want to feed to $.when
.
我认为问题是$ .each返回你的dataArray,而不是像你想要提供给$ .when的Deferred对象列表。
#1
21
as Eli pointed out, $.when() accepts a comma separated list of arguments and not an array. using Function.apply()
to pass in the array seems to do the trick.
正如Eli指出的那样,$ .when()接受逗号分隔的参数列表而不是数组。使用Function.apply()传入数组似乎可以解决问题。
function saveAll(callback) {
var dataArray = [], deferreds = [];
$.each(dataArray, function() {
deferreds.push( save() );
});
$.when.apply(window, deferreds).then(callback);
}
#2
1
You should be able to pass a comma-separated list of deferred objects to $.when
and .then
will execute once they all have resolved.
您应该能够将逗号分隔的延迟对象列表传递给$ .when和.then将在它们全部解析后执行。
http://api.jquery.com/jQuery.when/
http://api.jquery.com/jQuery.when/
#3
1
The problem I think is that $.each
is returning your dataArray
, not a list of Deferred
objects like you want to feed to $.when
.
我认为问题是$ .each返回你的dataArray,而不是像你想要提供给$ .when的Deferred对象列表。