javascript - Nodejs异步事件导致顺序错误

标签 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 核心同步运行, 控制台.log(newArray);是空的,我看不到所有新值。 我只想在 foreach 及其事件完成之后继续我的代码,而不是之前。

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

最佳答案

是的,async npm 会对这种情况有所帮助。

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

关于javascript - Nodejs异步事件导致顺序错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36008451/

相关文章:

javascript - 使用 Jquery 部分搜索 TABLE 中的单词

javascript - 我无法更新主干中的收藏

javascript - 未处理的 promise 拒绝警告 : error: password authentication failed for user

node.js - 使用 Passport js 进行身份验证时 Sequelize Js 错误(facebook)

javascript - Animate.css 与 Bootstrap 模态的交互,关闭动画的问题

javascript - 如何在 html 中为 iphone 禁用水平滚动

sql-server - SQL Server 繁琐的回调

javascript - 点击事件 : divs appear one at a time

android - 触摸事件不能很好地从子级发送到父级 - 添加源代码

javascript - 捕捉并停止中键点击