问题描述
我需要一些有关 node.js 异步特性的帮助.我有一个 for 循环,它从数据库中收集数据.result"是一个数组,然后应该返回给主函数.
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 这样的辅助库https://github.com/caolan/async
You might want to consider using helper library like asynchttps://github.com/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.
检查单元测试以获取示例
Checkout the unit tests for examples
https://github.com/caolan/async/blob/master/mocha_test/each.js
这篇关于在 node.js 中 for 循环完成后的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!