当function完成时Nodejscallback下一个循环

假设我们有一个脚本,它将为数组中的每一行执行特定的任务。

function execute(err, array){ loop(array, function(err,object){ console.log(object) //do a certain task when it's finished get into the next object successively. }); } function loop(array,callback){ array.forEach(function(object){ callback(null, object); }); } function array(callback){ callback(null, [1, 2, 3, 4, 5]); } setTimeout(function(){ array(execute); }, 6000); 

问题:

  • 如何完成任务后才能进入下一个循环?
  • 我的function被认为是asynchronous的?

尝试这个:

 function execute(err, array) { loop(array, function(err, object, next) { console.log(object); next(); // this will call recur inside loop function }, function() { console.log('All done'); }); } function loop(array, callback, finish) { var copy = array.slice(); (function recur() { var item = copy.shift(); if (item) { callback(null, item, recur); } else { if (typeof finish == 'function') { finish(); } } })(); } 

不,你的function不是asynchronous的,但你可以使用setTimeout来asynchronous调用它。

你可以做这样的事情迭代你的数组:

 var myarray = [1,2,3,4,5]; next(myarray, 0); function next(array, idx) { if (idx !== array.length) { // do something console.log(array[idx]); // run other functions with callback another_fct(array[idx], function() { next(array, idx + 1); // then the next loop }); // or run directly the next loop next(array, idx + 1); } else { // the entire array has been proceed console.log('an array of '+array.length+' number of elements have been proceed'); } } function another_fct(array_element, callback) { // do something with array_element console.log('value : '+array_element); callback(); // run the next loop after processing } 

这个方法将同步执行你的数组元素。

async为此提供了async.series和其他助手。

如果你重构代码并删除任何多余的匿名函数,你可以更好地围绕它。 这种情况是,传递一个匿名函数作为另一个函数的参数还没有使该函数asynchronous。 您在“是否进行callback使函数asynchronous?”中有更深入的解释。 。

从重构版本,

 setTimeout(function() { [1, 2, 3, 4, 5].forEach(function(object) { console.log(object) //do a certain task when it's... }); }, 6000); 

可以看出forEach被称为数组。 forEach方法为每个数组元素执行一次提供的函数并同步执行。

所以,要回答你的问题:

  1. 是的,只有在完成之前,它才会调用下一个项目(但是如果执行任何asynchronous操作,请参见下文)
  2. 这不被认为是asynchronous的,因为它不执行任何asynchronous操作(不考虑外部setTimeout

但是,如果您select在forEach函数中启动asynchronous操作,则事情会发生相当大的变化。 结果是所有操作都在同一时间进行中。 这在资源上是潜在的危险操作。 像async这样的库可以优雅地处理这个用例。

(顺便说一句,很好的使用Node.js errbacks,其中第一个函数参数保留用于传递潜在的错误。)