0

I want to have a callback called, when a async task is completed. Following is the code for the same:

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();

In the code above, callMeWhenDone callback method is not getting called after a async task is completed.

How can i call it within the async task.

1 Answer 1

2

That's because you've given your async task callback parameter the same name of callMeWhenDone. Give that parameter a different name like cb and then call them both when each task is done:

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);
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.