2014-02-25 41 views
1

我必须在node.js中实现一个类似下面的代码片段的程序。它有一个数组,但我必须遍历数据库表项并将其与值进行匹配。我需要等待,直到循环结束,将结果发送回调用函数: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函数之前异步执行,我无法遍历数组并获得所需的输出。

此外,我很难遍历数组,并将结果发回给调用函数,因为我没有任何想法会在何时完成循环。

回答

3

尝试使用异步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! 
}) 
+0

@ user3256628如果这个答案帮助你,请考虑标志着以此为回答这个问题。 – arb