gpt4 book ai didi

javascript - async each 中的异步任务 : Callback to be run after all task and sub tasks completed

转载 作者:行者123 更新时间:2023-11-29 23:15:50 27 4
gpt4 key购买 nike

为此,我正在使用 async.js。我基本上迭代所有数组并使用 aysnc.each 运行删除。

var async = require("async");
var fs = require('fs');


var files = ['a.log', 'b.log', 'c.log'];


async.each(files, function(file, cb) {
if(file == 'a.log') {
console.log('its A');
fs.unlink(file, function(err) { //delete the particular file
if(err) {
console.error(err);
}
console.log(file + ' has been Deleted');
});
}

if(file == 'b.log') {
console.log('its B');
fs.unlink(file, function(err) {
if(err) {
console.error(err);
}
console.log(file + ' has been Deleted');
});
}

if(file == 'c.log') {
console.log('its C');
fs.unlink(file, function(err) {
if(err) {
console.error(err);
}
console.log(file + ' has been Deleted');
});
}
cb();
}, function(err) {
console.log('all done');
});

我现在的输出..删除稍后完成。

its A
its B
its C
all done
a.log has been Deleted
b.log has been Deleted
c.log has been Deleted

我想要实现的是输出类似于下面的内容,其中回调仅在所有每个子任务(删除文件)完成后运行。

its A
its B
its C
a.log has been Deleted
b.log has been Deleted
c.log has been Deleted
all done //would like this

最佳答案

您的迭代对象的回调被调用得太早(它没有等待 fs.unlink 完成)。
您需要在 fs.unlink 回调中移动对它的调用:

async.each(files, function(file, cb) {
if(file == 'a.log') {
...
} else if(file == 'b.log') {
...
} else if(file == 'c.log') {
...
}
...
fs.unlink(file, function(err) {
...
cb();
...
}
...
}, function(err) {
console.log('all done');
});

关于javascript - async each 中的异步任务 : Callback to be run after all task and sub tasks completed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52827493/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com