NodeJS循环等待callback
我如何等待一个for循环,直到收到callback,然后继续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."); }
感谢您的投入!
如果被调用的方法是asynchronous的,则可能无法使用循环,而是可以使用基于recursion的解决scheme
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>
发电机是你的朋友在这里: 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)) }); }