Nodejsasynchronous事件导致错误的顺序

比方说,我有一个函数内的以下function:

function (arr){ newArray = []; arr.forEach(function(prop){ //extract data from arr into newArray with newArray.push(), //this is done through fs and ffmpeg events } console.log(newArray); //empty, because of async problems //I want to proceed with my code here } 

现在你可以看到,我从一个旧数组中提取数据到一个新数组中,每个newArray.push都是通过一个包含fs和FFmpeg等包的事件完成的,只有当你没有任何东西时才会运行问题是,由于JS内核同步运行,console.log(newArray); 是空的,我看不到所有的新值。 我只是想继续我的代码后为每个事件完成,而不是之前。

那么,我该如何解决这个问题呢? asynchronous包可能会有所帮助?

是的asynchronousNPM将有助于这种情况。

 async.eachSeries(arr, function(item, callback) { fs.writeFile(item, item, function(err) { if(!err) { newArray.push(item); } callback(); }); }, function done() { console.log(newArray) }); 

如果你正在等待你的数组被填充,你可以使用asynchronous每个方法:

 async.each(arr, function(prop, callback) { // your code to proceed with the item // call callback() once you want to move on the next item }, function(err){ if( err ) { console.log('An item failed to process'); } else { // this is where you can play with newArray[] now that it's filled // console.log(newArray) shouldn't show you empty console.log('All items have been processed successfully'); } }); 

问题是,你的arr.forEach内部函数在你调用console.log(newArray)之后填充console.log(newArray)

除了async之类的库或者更好的co (使用Promise)之外,你可以像这样手动添加一个callback函数:

 function (arr){ newArray = []; cnt = arr.length arr.forEach(function(prop){ ... cnt-- if (cnt == 0) { console.log(newArray) } } } 

随着你可能会使用Array.map而不是Array.forEach ,写这样的事情:

 newArray = yield arr.map(co.wrap(function*(prop) { ... return elem })) console.log(newArray)