NodeJS异步在任务完成之前完成

时间:2016-03-29 11:42:08

标签: node.js asynchronous mongoose

我遇到了问题,基本上我想在异步瀑布完成后调用一个函数。问题是我调用了更新,但它在我的更新完成之前继续。我想调用的函数取决于已更新的数据。

甚至没有发送消息。但它最终会在数据库中更新。

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!
            }
        });
    }

所有代码:

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

2 个答案:

答案 0 :(得分:1)

您忘了等newPeople.save完成。将回调函数的调用放在回调中。 (callception)

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

答案 1 :(得分:0)

在最后一行使用.then()并在那里添加你的功能。