环路
问题描述:
所以每次迭代等待异步.done(),我有功能锁定这样的:环路
function getMainData() {
var dfd = $.Deferred();
$.getJSON('My string that i pass',
function(result) {
if (result !== undefined) {
dfd.resolve(result);
}
})
return dfd.promise()
}
function getSpecificData() {
var dfd = $.Deferred();
var myArray = [];
for (var i = 0; i < 5; i++) {
getMainData().done(function(result) {
myArray.push(result)
dfd.resolve(myArray) //This is where I am lost.
})
}
return dfd.promise()
}
getSpecificData().done(function(result) {
console.log(result);
})
我想我知道,如果你把它们连在一起的承诺是如何工作的,但我不能让for-loop在下一次迭代之前等待异步调用完成。
能有些帮助我吗?
答
一种用于环路具有延迟下一次迭代等待异步代码的手段。
您可以通过使用一个被递归调用,而不是
function getMainData() {
return $.getJSON('My string that i pass');
}
function getSpecificData() {
var myArray = [], def = new $.Deferred();
(function rec(i) {
getMainData().done(function(result) {
myArray.push(result);
if (i < 5 && result !== undefined) {
console.log(i)
rec(++i);
} else {
def.resolve(myArray);
}
});
})(0);
return def.promise();
}
getSpecificData().done(function(result) {
console.log(result);
});
答
你试过没有promise
像:
var myArray = [];
var cpt=0;
var total=5;
getMainData();
console.log(myArray);
function getMainData()
{
$.getJSON('My string that i pass', function(result) {
if(cpt<total)
{
myArray.push(result);
cpt++;
getMainData();
}
})
}
希望这有助于。
答
而是应该推动所有的承诺到一个数组中,并等待所有到结束。
function getMainData() {
return $.getJSON('My string that i pass');
}
function getSpecificData() {
var promiseArray = [];
for (var i = 0; i < 5; i++) {
promiseArray.push(getMainData());
}
return $.when.apply($, promiseArray);
}
getSpecificData().done(function(result) {
console.log(result);
})
+0
感谢一个很好的解决方案功能解决这个问题,但预期这是行不通的。我没有从我所有的异步调用中获取值。这意味着该循环不会等待异步调用。 – Zorken17
+0
@ Zorken17您可以使用参数变量获得全额返还列表,而不是结果的变量 –
谢谢你的解决方案,这个结果不错,而我其实是没有考虑过递归方法。 – Zorken17