gpt4 book ai didi

javascript - Node JS 数组、Foreach、Mongoose、同步

转载 作者:行者123 更新时间:2023-12-03 05:52:50 25 4
gpt4 key购买 nike

我对 Node js 还没有那么丰富的经验,但我正在学习。

所以我的问题。例子:我有一个带有 Mongoose 和异步模块的小应用程序。在 mongodb 的用户集合中,我有 1 个用户,其字段余额 = 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 ,我已经尝试过 every、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

谢谢

最佳答案

问题在于调用最终回调的位置。您需要在 waterfall 的最终回调内部调用 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

});

关于javascript - Node JS 数组、Foreach、Mongoose、同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40074540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com