问题描述
我正在尝试更新用户行中的特定字段,并且我正在使用forEach循环来执行此操作,但这只是最后一次运行的循环被更新。 这是我的代码的样子:
<?PHP echo $_GET['user']?>
运行此代码后,用户的余额应为“ 300”,而应为“ 200”。这就像最后一个要覆盖第一个,因为它们以非常接近的间隔运行,我不能;只是把我的头缠起来...请怎么解决?
解决方法
您在这里处理的是异步循环,但是代码不会等到承诺完成后再移到下一个。
使用async
函数要容易得多。
async function updateBalances(userID,updates){
for (const update of updates) {
const user = await UserSchema.findByID(userID)
user.balance += update
await user.save()
}
console.log('user balances updated')
}