假设我在函数中有以下函数:
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/