How to handle async concurrent requests correctly?

后端 未结 2 739
借酒劲吻你
借酒劲吻你 2020-12-15 02:58

Let\'s say I have some sort of game. I have a buyItem function like this:

buyItem: function (req, res) {
    // query the users balance
    // deduct user ba         


        
2条回答
  •  攒了一身酷
    2020-12-15 03:34

    I haven't tested this out. But as long as your not using multiple instances or clusters, you should just be able to store the status in memory. Because node is single threaded there shouldn't be any problems with atomicity.

    var inProgress = {};
    
    function buyItem(req, res) {
        if (inProgress[req.session.user.id]) {
            // send error response
            return;
        }
    
        inProgress[req.session.user.id] = true;
    
        // or whatever the function is..
        req.session.user.subtractBalance(10.00, function(err, success) {
            delete inProgress[req.session.user.id];
    
            // send success response
        });
    }
    

提交回复
热议问题