NodeJS循环等待回调

问题描述:

如何在for循环中等待,直到收到回调,然后继续for循环?NodeJS循环等待回调

这里是我的循环:

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."); 
} 

感谢输入!

+1

您可能无法在for循环中执行此操作,因为'doSomething'看起来像是一个异步方法 –

+0

有什么可以作为我想要的另一个选项? @ArunPJohny –

+1

https://jsfiddle.net/arunpjohny/h38wt723/1/ - 尝试像 –

你可能不能够使用一个循环,如果所调用的方法是异步的,而不是你可以使用基于递归的解决方案就像

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>

+0

请不要调用函数'x'。 – Amberlamps

发电机是你的朋友在这里: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)) 
    }); 
}