最好的方式使用循环和aysnc水落在一起

我是Nodejs的新手,需要一些编写更好的代码的指导。 这是我的问题。

我有一个function,我正在使用asynchronous降水模型。 我想在一个循环中调用这个函数,如果在中间出错了,则在循环结束时通知一些结果。 但由于某种原因,我收到了一个未定义的回应。

function myFunc (arg1) { async.waterfall( [ function() { //do something callback(null, data); }, function(data, callback) { //do something callback(null, 'done'); } ], function(err, result) { return {"error" : err, "res" : result}; } } //Here I am calling my function for (var d in mydata) { var retdata = myFunc (mydata[d]); //retdata has undefined in it as this line executes before the last function of water fall if (retdata.error !== 200) { return // break loop } } //Other wise if every thing is fine nofify after the for loop end console.log ("done"); 

总之,在瀑布的最后一个function给出错误的时候,最后通知结果的正确和最好的方法是什么(如果是的话)或者是断开循环。

您不能使用同步方法(如for循环),并期望您的代码等待asynchronous任务完成。 您不能使用返回从asynchronous函数中获取数据。

这是一种使用async.map重构代码的方法。 记下callback结构。 另外请确定您所指的是asynchronous文档 。

 //Async's methods take arrays: var mydata = {a: 'foo', b: 'bar'}; var myarr; for (var d in mydata) { myarr.push(mydata[d]); // Beware, you might get unwanted Object properties // see eg http://stackoverflow.com/questions/3010840/loop-through-array-in-javascript/3010848#3010848 } async.map(myarr, iterator, mapCallback); function iterator(d, done){ // async.map will call this once per myarr element, until completion or error myFunc(d, function(err, data){ done(err, data); }); }; function mapCallback(err, mapped){ // async.map will call this after completion or error if(err){ // Async ALREADY broke the loop for you. // Execution doesn't continue if the iterator function callsback with an // error. }; console.log("Asynchronous result of passing mydata to myfunc:"); console.log(mapped); // mapped is an array of returned data, in order, matching myarr. }; function myFunc (arg1, callback) { async.waterfall( [ function(done) { //do something done(null, data); }, function(data, done) { //do something done(null, 'done'); } ], function(err, result) { if (result !== 200) { return callback('Non-200'); // This return is important to end execution so you don't call the callback twice } callback(err, result); } } 

您正在尝试混合同步和asynchronous控制stream。 问题在于myFunc中的任何一个瀑布函数在执行之前都会立即返回给myFunc。

这是一个真正的例子,将工作。 它遍历数组,如果看到一个5:

 var async = require('async'); function myFunc(data, cb) { async.waterfall( [ function(callback) { //do something callback(null, data); }, function(data, callback) { //do something if (data === 5) { callback("Five", null); // Throw error if we see 5 } else { callback(null, 'done'); } } ], function(err, result) { cb(err, result); } ); } var mydata = [1,2,3,4,5,6]; async.eachSeries(mydata, function(d, cb) { console.log('Processing ' + d); myFunc(d, cb); }, function(err) { // error happened in processing d // handle error console.log('Error ' + err); });