Dave Cooper
Dave Cooper

Reputation: 10714

Ensure two functions execute one after the other, where the first function has an asynchronous call inside it

I am trying to use the async.js library to achieve the following:

So far I have gathered I should be using the series() function from the async library. This is what I have so far:

async.series([
    function(callback) {
       var someResult = a();
       callback(null, someResult);
    },
    function(callback) {
        var someOtherResult = b();
        callback(null, someOtherResult);
    }
],
function(err, results) {
    console.log('Yay');
});

This is pretty similar to the code outlined in the documentation for async.js, but inside a() there is some other async activity going on.

I want to wait until all activity inside of a() has finished before executing b(). Is this possible? If I need to modify the contents of a(), what would need to be done? I'm aware that this sort of question goes against how things are supposed to be written in node (and js in general), but the async operation going on inside of a() is a database query.

Happy to give more info if needed!

Thanks!

Upvotes: 0

Views: 2317

Answers (1)

slebetman
slebetman

Reputation: 113876

All async functions must accept callbacks (or return a promise). Otherwise it's not possible to execute something after the async function has completed.

So, since a() is async. I'd assume that your example:

var someResult = a();

is a typo. It should be:

a(function(someResult){
   // ...
})

There is no way around this. You cannot pause the interpreter and wait for an async function to complete because pausing the interpreter will also pause the event loop causing the async function to never complete.

If a() is properly written, you should be able to just do this:

async.series([
    function(callback) {
       a(function(someResult){
           callback(null, someResult);
       });
    },
    function(callback) {
        var someOtherResult = b();
        callback(null, someOtherResult);
    }
],
function(err, results) {
    console.log('Yay');
});

If not, send a() back to the person who wrote it and tell him he's doing it wrong.

Upvotes: 1

Related Questions