每个异步内部的异步任务:在所有任务和子任务完成后运行回调

时间:2018-10-16 03:18:18

标签: javascript node.js async.js

我为此使用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

3 个答案:

答案 0 :(得分:1)

调用iteratee的回调为时过早(它不等待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');
});

答案 1 :(得分:0)

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

var files = ['a.log', 'b.log', 'c.log'];
var dict = { 'a.log': 'A', 'b.log': 'B', 'c.log': 'C' };

async.each(files, function(file, cb) {
  console.log('its ' + dict[file]);
  fs.unlink(file, function(err) {
    if(err) {
      console.error(err)
      cb(err)
    } else {
      console.log(file + ' has been Deleted');
      cb()
    }
  })
}, function(err) {
  console.log('all done');
});

您应该将回调调用移到unlink函数中。 我还删除了冗余代码。

答案 2 :(得分:0)

尝试下一个

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


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

async.each(files, function (file, cb) {
  console.log(file);
  fs.unlinkSync(file);  //delete the particular file
  console.log(file + ' has been Deleted');
  cb();
}, function (err) {

  console.log('error = ', err);
}
);
console.log('All done');