在node.js中完成for循环后的回调

编程入门 行业动态 更新时间:2024-10-23 19:28:59
本文介绍了在node.js中完成for循环后的回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要一些有关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循环后的回调

本文发布于:2023-11-25 04:07:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628256.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:回调   node   js

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!