【问题标题】:Node JS Array, Foreach, Mongoose, SynchronousNode JS 数组、Foreach、Mongoose、同步
【发布时间】:2016-10-17 04:44:22
【问题描述】:

我对 node js 的经验还不是很丰富,但我正在学习。

所以我的问题。例子: 我有一个带有猫鼬和异步模块的小应用程序。在用户集合中的 mongodb 中,我有 1 个用户的字段 balance = 100 。

var arr     = [1,2,3,4];
var userId  = 1;
async.forEachSeries(arr, (item, cb) =>{
    async.waterfall([
        next => {
            users.findById(userId, (err, user) =>{
                if (err) throw err;
                next(null, user)
            });
        },
        (userResult,next) =>{
            var newBalance = userResult.balance - item;
            users.findByIdAndUpdate(userId, {balance:newBalance}, err =>{
                if (err) throw err;
                next(null, userResult, newBalance);
            })
        }

    ],(err, userResult, newBalance) =>{
        console.log(`Old user balance: ${userResult.balance} New user balance: ${newBalance}`);
    });
    cb(null)
});

我收到了这样的结果

Old user balance: 100 New user balance: 98
Old user balance: 100 New user balance: 99
Old user balance: 100 New user balance: 97
Old user balance: 100 New user balance: 96

所以基本上 foreach 异步调用 async.waterfall 。我的问题是如何逐项进行 foreach 同步,我已经尝试了 each, forEach, eachSeries ,有和没有 Promises。最后需要得到这样的结果

Old user balance: 100 New user balance: 99
Old user balance: 99 New user balance: 97
Old user balance: 97 New user balance: 94
Old user balance: 94 New user balance: 90

谢谢

【问题讨论】:

    标签: javascript arrays node.js mongodb mongoose


    【解决方案1】:

    问题在于调用最终回调的位置。您需要在瀑布的最终回调内部而不是外部调用 cb():

    var arr     = [1,2,3,4];
    var userId  = 1;
    async.forEachSeries(arr, (item, cb) =>{
      async.waterfall([
        next => {
            users.findById(userId, (err, user) =>{
                if (err) throw err;
                next(null, user)
            });
        },
        (userResult,next) =>{
            var newBalance = userResult.balance - item;
            users.findByIdAndUpdate(userId, {balance:newBalance}, err =>{
                if (err) throw err;
                next(null, userResult, newBalance);
            })
        }
    
    ],(err, userResult, newBalance) =>{
        console.log(`Old user balance: ${userResult.balance} New user balance: ${newBalance}`);
        cb(null);   // <<==== call here
    });
    // cb(null);   // <<==== NOT call here
    

    });

    【讨论】:

      猜你喜欢
      • 2018-10-27
      • 2015-01-06
      • 2017-12-09
      • 2022-06-14
      • 2014-11-09
      • 2021-06-17
      • 2018-05-15
      • 1970-01-01
      • 2019-09-09
      相关资源
      最近更新 更多