如何识别循环已完成

时间:2014-08-29 17:52:54

标签: javascript node.js foreach

我想尽量减少以下代码。在节点js

中工作
var each = 0;
var final = {};
// myLoop have some array values;
myLoop.forEach(function(row) {

    //data retrive from db
    db.query('SELECT * FROM test where type=?',[row.type], function(err, result) {
        final[each] = result;
        each++;
        if (each == myLoop.length) {
           return final;
        }
    });

});

以上代码工作正常,但试图避免 if(each == myLoop.length)条件。 是否有可用于识别循环的完成?

可能如下所示:

myLoop.forEach(function(row) {
    //do needs
}).done({
    return final;
});

4 个答案:

答案 0 :(得分:1)

看起来你的需要应该与DB方合作。

即使async.each确定是否所有回调都通过计算完成

如果将MongoDB与节点驱动程序一起使用, 您可以尝试在aggregation

中发出查询

答案 1 :(得分:0)

你可以通过Caolan的Async库来实现这个目的(或者你可以看看它是如何在这个库中完成的) - https://github.com/caolan/async#each

// assuming openFiles is an array of file names 

async.each(openFiles, function( file, callback) {

  // Perform operation on file here.
  console.log('Processing file ' + file);

  if( file.length > 32 ) {
    console.log('This file name is too long');
    callback('File name too long');
  } else {
    // Do work to process file here
    console.log('File processed');
    callback();
  }
}, function(err){
    // if any of the file processing produced an error, err would equal that error
    if( err ) {
      // One of the iterations produced an error.
      // All processing will now stop.
      console.log('A file failed to process');
    } else {
      console.log('All files have been processed successfully');
    }
});

答案 2 :(得分:0)

从短期来看,你可以使用forEach的索引:

var final = {};
// myLoop have some array values;
myLoop.forEach( function( row, index ) {
    //data retrive from db
    final[ index ] = row;
    if (index === myLoop.length) {
        return final;
    }
});

你为什么要回“最后”?你希望做一些事情,比如触发一个事件吗?

答案 3 :(得分:0)

您可以使用回调函数。只有在一切都完成后才能执行。

 // Call the function
 loopTheArray(myLoop,function(final){
    //Do whatever you want with final
 });

function loopTheArray(myLoop,callback){
    var final = {},each=0;
    myLoop.forEach(function(row) {
        //data retrive from db
        final[each] = row;
    });
    callback(final);
}

Working Fiddle