Nodejs异步事件导致错误的顺序

时间:2016-03-15 10:19:48

标签: javascript node.js events asynchronous

假设我在函数中有以下函数:

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);是空的,我看不到所有新的价值观。 我只是想在每个事件之后继续我的代码并且它的事件已经完成,而不是之前。

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

3 个答案:

答案 0 :(得分:0)

如果您正在等待填充阵列,可以使用async each方法:

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

答案 1 :(得分:0)

是的异步npm对这种情况有帮助。

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

答案 2 :(得分:0)

问题是,在您致电arr.forEach之后,newArray内部功能会填满console.log(newArray)

除了像async这样的库或者更好的co(使用Promises)之外,你可以像这样手动添加回调:

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

使用co,您可以使用Array.map代替Array.forEach并写下这样的内容:

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