【发布时间】: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