Braeden Dillon
Braeden Dillon

Reputation: 99

NodeJS async finishes before task is complete

I'm having a problem, basically I want to call a function once this async waterfall is complete. The problem is I call an update, but it continues on before my update completes. The function I want to call depends on this data already been updated.

The message isn't even been sent. But it eventually will update in the database.

function(arg1, arg2, callback) {
    console.log('Updating current_pot with amountInPot');
    current_pot.findOneAndUpdate(
        {}, 
        {'amountInPot': currentlyInPot}, 
        function(err, current) {
            if (err) {
                throw err;
            }
            if (current != null) {
                console.log('Updated current_pot amountInPot');
                callback(null, 'c');
                //This message should be sent before the callback continues!
            }
        });
    }

All the code:

async.waterfall([
    function(callback) {
        //remove from db
        console.log('Add to local pot!');
        currentlyInPot++;
        peopleInPot.push([user.local.picture, message[1], user.local.email]);
        callback(null, 'a', 'b');
    },
    function(arg1, arg2, callback) {
        console.log('Updating persons credits');
        callback(null, 'c', 'd');
    },
    function(arg1, arg2, callback) {
        console.log('Adding new people to db');
        var newPeople = new people_pot();
        newPeople.email = user.local.email; //Auto increment
        newPeople.picture = user.local.picture;
        newPeople.message = message[1];

        /** success starts */
        newPeople.save(function(err) {
            if (err) {
                throw err;
            }
        });

        callback(null, 'a', 'b');
    },
    function(arg1, arg2, callback) {
        console.log('Updating current_pot with amountInPot');
        current_pot.findOneAndUpdate({}, {
             'amountInPot': currentlyInPot
        }, 
    function(err, current) {
        if (err) {
            throw err;
        }
        if (current != null) {
            console.log('Updated current_pot amountInPot');
            callback(null, 'c');
            //This isn't getting completed before the loadpot is called!
        }
    });
}
], function(err, result) {
    // result is 'e'
    //add to db
});

Upvotes: 0

Views: 155

Answers (2)

Tamas Hegedus
Tamas Hegedus

Reputation: 29926

You forgot to wait for newPeople.save to complete. Put the call of the callback function in the callback. (callception)

    /** success starts */
    newPeople.save(function(err) {
        callback(err, 'a', 'b');
    });

Upvotes: 1

Rahul Jain
Rahul Jain

Reputation: 3748

use .then() in last line and add your function there.

Upvotes: 0

Related Questions