gpt4 book ai didi

Node.js for 同步方式循环执行

转载 作者:太空宇宙 更新时间:2023-11-03 22:54:59 26 4
gpt4 key购买 nike

我必须在 node.js 中实现一个程序,如下所示的代码片段。它有一个数组,我必须遍历该数组并将值与数据库表条目进行匹配。我需要等到循环结束并将结果发送回调用函数:

var arr=[];
arr=[one,two,three,four,five];

for(int j=0;j<arr.length;j++) {

var str="/^"+arr[j]+"/";

// consider collection to be a variable to point to a database table

collection.find({value:str}).toArray(function getResult(err, result) {
//do something incase a mathc is found in the database...
});

}

但是,由于 str="/^"+arr[j]+"/"; (实际上是传递给 MongoDB 的 find 函数的正则表达式,以便找到部分匹配) )在 find 函数之前异步执行,我无法遍历数组并获得所需的输出。

此外,我很难遍历数组并将结果发送回调用函数,因为我不知道循环何时完成执行。

最佳答案

尝试使用异步each。这将允许您迭代数组并执行异步函数。 Async 是一个很棒的库,它为许多常见的异步模式和问题提供了解决方案和帮助程序。

https://github.com/caolan/async#each

类似这样的事情:

var arr=[];
arr=[one,two,three,four,five];

asych.each(arr, function (item, callback) {
var str="/^"+item+"/";
// consider collection to be a variable to point to a database table
collection.find({value:str}).toArray(function getResult(err, result) {
if (err) { return callback(err); }
// do something incase a mathc is found in the database...
// whatever logic you want to do on result should go here, then execute callback
// to indicate that this iteration is complete
callback(null);
});
} function (error) {
// At this point, the each loop is done and you can continue processing here
// Be sure to check for errors!
})

关于Node.js for 同步方式循环执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22016246/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com