【问题标题】:Synchronization multi request payment express nodejs同步多请求支付快递nodejs
【发布时间】:2018-04-10 01:10:47
【问题描述】:

今天我正在用 mongoose 构建 RESTful API 充值。这包括增加和减少。我希望金额永远不会低于 0。

如果多个请求增加一个帐户,则没有问题。但是我要求非常非常快的多请求充值帐户它坏了!!!!

这是一个减少账户资金的例子:

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 money = 5000

然后在 0.001 秒内发出快速 10 请求。然后我检查我的数据库它显示钱 -25000

不是同步吗?

为什么if(user.money &lt;= 0) return res.json({message: "Not enough money"}); 不起作用?

请帮帮我。每个答案都会被接受!

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    使用方括号 {} 可能会有所帮助,而且您对 return res.json({message: "Give success"}); 的调用将在 user.save(); 完成之前完成。

    async-await 下面给出的示例省略了错误处理。

    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"});
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-09
      • 2014-07-30
      • 2011-06-06
      • 2023-04-04
      • 1970-01-01
      相关资源
      最近更新 更多