【问题标题】:NodeJS async finishes before task is completeNodeJS异步在任务完成之前完成
【发布时间】:2016-07-16 22:45:56
【问题描述】:

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

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

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

【问题讨论】:

    标签: node.js asynchronous mongoose


    【解决方案1】:

    您忘记等待newPeople.save 完成。将回调函数的调用放入回调中。 (呼叫接收)

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多