如何在for循环中等待,直到收到回调,然后继续for循环?
这是我的循环:
for(var i = 0; i < offer.items_to_receive.length; i++) {
console.log("Waiting for callback...");
doSomething(function(data) {
console.log("Got data from callback! " + data);
});
console.log("Continue for loop now.");
}
感谢您的投入!
答案 0 :(得分:2)
如果被调用的方法是异步的,您可能无法使用循环,而是可以使用基于递归的解决方案,如
function x(items, i) {
i = i || 0;
if (i >= items.length) {
return
}
snippet.log("Waiting for callback..." + i);
doSomething(function(data) {
snippet.log("Got data from callback! " + data);
if (i == items.length - 1) {
snippet.log("completed");
} else {
x(items, i + 1)
}
});
}
// a sample implementation of asynchronous method
var counter = 0;
function doSomething(cb) {
setTimeout(cb.bind(window, counter++), 100)
}
x([1, 2, 3, 4])
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
答案 1 :(得分:0)
发电机是您的朋友:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators
但如果你还没有准备好ES6,那么@Arun P Johny的帖子概念可能有所帮助:
function getData(items) {
if (!items.length) {
return;
}
doAsyncCall(items[0], function(data) {
getData(items.slice(1))
});
}