我希望在完成异步任务时调用回调函数。以下是相同的代码:
var async = require("async");
function callMeWhenDone(err, result){
if(err) console.log('Error Occurred');
console.log('Callback called');
console.dir(result);
}
function tasks() {
console.log('Start executing tasks');
var tasks = [];
var result = {};
tasks.push(function(callMeWhenDone) {
console.log('Getting some data');
callMeWhenDone(null, result);
});
tasks.push(function(callMeWhenDone) {
console.log('Second function called');
callMeWhenDone(null, result);
});
async.series(tasks, function(err, result){
console.log('All done');
callMeWhenDone(err, result);
});
}
tasks();
在上面的代码中,异步任务完成后,不会调用callMeWhenDone
回调方法。
如何在异步任务中调用它。
答案 0 :(得分:2)
这是因为您已将async
任务回调参数命名为callMeWhenDone
。为该参数指定一个不同的名称,如cb
,然后在每个任务完成时调用它们:
function tasks() {
console.log('Start executing tasks');
var tasks = [];
var result = {};
tasks.push(function(cb) {
console.log('Getting some data');
callMeWhenDone(null, result);
cb(null, result);
});
tasks.push(function(cb) {
console.log('Second function called');
callMeWhenDone(null, result);
cb(null, result);
});
async.series(tasks, function(err, result){
console.log('All done');
callMeWhenDone(err, result);
});
}