同步多请求支付Express Node.js [英] Synchronization multi request payment express nodejs
问题描述
今天,我正在用猫鼬构建RESTful API充值资金.这包括增加和减少.我希望金额永远不会超过0.
Today I am building RESTful API recharge money with mongoose. This include increase and decrease. I want amount never get bellow than 0.
如果多个请求增加一个帐户,没问题.但我要求非常快速的多要求充值帐户坏了!!!!
No problem if multi request increase by one account. But I request very very fast multi request recharge a account It broken!!!!
这是一个减少帐户资金的示例:
This is a example decrease money of a account:
app.post("/recharge",function(req,res){
Bottle.findById({user: "foo"}, function (err, user) {
if(user.money <= 0) return res.json({message: "Not enough money"});
else {
user.money -=5000;
user.save();
return res.json({message: "Give success"});
}
})
}
我设置了 foo 钱= 5000
然后在0.001秒内发出10个快速请求.然后我检查我的数据库,它显示fo money -25000
Then a make fast 10 request in 0.001s. Then I check my database It show fo money -25000
不是同步吗?
为什么 if(user.money< = 0)返回res.json({message:没有足够的钱"});
无效?
请帮帮我.每个答案都会被接受!
Help me please. Every answer will be accepted!
推荐答案
使用方括号 {}
可能会有所帮助,并且您调用返回res.json({message:"Give成功});
将在 user.save();
完成之前完成.
It may help to use brackets {}
and also your call to return res.json({message: "Give success"});
will complete BEFORE user.save();
is complete.
async-await
示例,省略了错误处理.
async-await
example given below with error handling omitted.
app.post("/recharge", async (req,res) => {
const user = await Bottle.findById({user: "foo"}).exec();
if (user.money <= 0) {
res.json({message: "Not enough money"});
return;
}
user.money -= 5000;
await user.save()
res.json({message: "Give success"});
}
这篇关于同步多请求支付Express Node.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!