如何识别循环已完成

我想尽量减less下面的代码。 在节点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; } }); }); 

上面的代码工作正常,但试图避免如果(每个== myLoop.length)条件。 有什么可用来确定循环完成?

有可能是这样的:

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

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

即使是async.each决定是否所有的callback都是通过计数完成的

如果您将MongoDB与节点驱动程序一起使用,则可以尝试在aggregation发出您的查询

你可以通过Caolan的asynchronous库(或者你可以看看它是如何在这个库中完成的) – 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'); } }); 

那么在短期内,你可以利用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; } }); 

而你为什么回到'最后'? 你是否希望做一些事情而不是触发事件呢?

您可以使用callback函数。 只有当一切完成后才会执行。

  // 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); } 

工作小提琴