【发布时间】:2019-03-20 12:23:42
【问题描述】:
我为此目的使用 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回调中移动async.eachiteratee回调(cb())的调用 -
移动到所有 3 个 fs.unlink 回调?
-
是...或者您可以重构代码,使其只有一个
fs.unlink...您的示例确实有很多重复...
标签: javascript node.js async.js