node.js以同步的方式执行循环

我必须在Node.js中实现一个类似下面的代码片断的程序。 它有一个数组,虽然我不得不遍历并与数据库表项匹配的值。 我需要等到循环结束并将结果发送callback用函数:

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]+"/"; (这实际上是一个正则expression式来传递给MongoDB的查找函数,以便find部分匹配)在find函数之前asynchronous执行,我无法遍历数组并获得所需的输出。

此外,我有困难的时间遍历数组,并将结果发callback用函数,因为我不知道什么时候循环完成执行。

尝试使用eachasynchronous。 这将让你迭代一个数组并执行asynchronous函数。 asynchronous是一个伟大的库,有许多常见的asynchronous模式和问题的解决scheme和帮手。

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! })