我需要一些有关node.js异步性质的帮助。我有一个for循环,它从数据库中收集数据。 result是一个数组,然后应该返回到main函数。
I need some help with the asynchronous nature of node.js. I have a for loop, which collects data from the database. "result" is an array, which should then be returned to the main function.
user_collection.findOne({ _id : uid }, function(error, user) { if(error) callback(error) else { for(var j = 0; j < user.contacts.length; j++) { if(user.contacts[j].accepted == 'true') { user_collection.findOne({ _id : user.contacts[j].contactId }, function(error, user) { result.push(user); }) } } callback(null, result); // This callback executes before the for-loop ends, ofc } });如何在循环结束后确保回调执行?
How can I ensure that the callback executes after the loop finished?
推荐答案您可能需要考虑使用辅助库,例如 async github/caolan/async
You might want to consider using helper library like async github/caolan/async
它有助于保持代码更加一致..
It helps keep code more consistent..
在您的情况下,您可以查看 forEach()方法
In your case, you can look at the forEach() method
forEach(arr, iterator, callback)使用列表中的项目和完成时的回调调用迭代器。
The iterator is called with an item from the list and a callback for when it has finished.
查看单元测试示例
github/caolan/async/blob/master/mocha_test/each.js
更多推荐
在node.js中完成for循环后的回调
发布评论