当我有可变数量的 ajax 请求时,如何使用 deferreds 调用它们?
我猜:
//qty_of_gets = 3;
function getHTML(productID, qty_of_gets){
var dfd = $.Deferred(),
i = 0,
c = 0;
//this is where there could be some magic to
//do multiple ajax posts
//obviously I'm out of my depth here...
while (i <= qty_of_gets){
dfd.pipe(function(){
$.get("queries/html/" + product_id + i + ".php");
});
i++
}
dfd.done(function(){
while (c <= qty_of_gets){
$('myDiv').append(c);
c++;
}
});
}
如果要顺序执行 Ajax 调用,则必须从回调返回 Promise,并将新的回调附加到最后一个 Promise 对象:
var dfd = $.Deferred(),
promise = dfd.promise(),
i = 0,
c = 0;
while (i <= qty_of_gets) {
// needs an IIFE
(function(i)
promise = promise.then(function(){
return $.get("queries/html/" + product_id + i + ".php");
});
}(i++));
}
promise.done(function(){
while (c <= qty_of_gets){
$('myDiv').append(c);
c++;
}
});
// resolve deferred
dfd.resolve();
从 jQuery 1.8 开始,你应该使用.then
代替.pipe
.
另一个问题是(至少在您的示例中)在执行回调时,i
不会有你期望的价值。您可以使用立即调用函数表达式捕获当前值i
. See 循环内的 JavaScript 闭包 – 简单的实际示例 https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example了解更多信息。
没有干净的解决方案来获得结果。我认为你能做的最好的事情就是将结果添加到一个数组中并在.done
打回来。 IE。:
var results = [];
while (i <= qty_of_gets) {
// needs an IIFE
(function(i)
promise = promise.then(function(){
return $.get("queries/html/" + product_id + i + ".php")
.then(function(result) {
results[i] = result;
});
});
}(i++));
}
promise.done(function(){
// do something with `results`
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)