如何正确处理异步并发请求?

Mar*_*n19 2 concurrency node.js express sails.js

假设我有某种游戏.我有一个像这样的buyItem函数:

buyItem: function (req, res) {
    // query the users balance
    // deduct user balance
    // buy the item
}
Run Code Online (Sandbox Code Playgroud)

如果我在扣除用户余额之前发送该路由(第二个查询),则用户的余额仍为正数.

我尝试过的:

buyItem: function (req, res) {
    if(req.session.user.busy) return false;
    req.session.user.busy = true;
    // query the users balance
    // deduct user balance
    // buy the item
}
Run Code Online (Sandbox Code Playgroud)

问题是req.session.user.busyundefined在第一〜5项要求.所以这也不起作用.

我们如何处理这种情况?我正在使用Sails.JS框架,如果这很重要的话.

sgr*_*454 14

更新2

Sails 1.0现在通过该方法提供完整的事务支持.getDatastore().例:

// Get a reference to the default datastore, and start a transaction.
await sails.getDatastore().transaction(async (db, proceed)=> {
  // Now that we have a connection instance in `db`, pass it to Waterline
  // methods using `.usingConnection()` to make them part of the transaction:
  await BankAccount.update({ balance: 5000 }).usingConnection(db);
  // If an error is thrown, the transaction will be rolled back.
  // Or, you can catch errors yourself and call `proceed(err)`.
  // To commit the transaction, call `proceed()`
  return proceed();
  // You can also return a result with `proceed(null, result)`.
});
Run Code Online (Sandbox Code Playgroud)

更新

正如一些评论者所指出的那样,当启用连接池时,下面的代码不起作用.在这个最初发布,并非所有的默认汇集适配器的,但在这一点上应该假定他们这样做,让每一个人的方法调用(时间.query(),.findOne()等)可以在不同的连接,在交易之外经营.Waterline的下一个主要版本将具有事务支持,但在此之前,确保查询是事务性的唯一方法是使用原始数据库驱动程序包(例如pgmysql).

听起来你需要的是交易.Sails不支持框架级别的事务(它在路线图上),但如果您使用支持它们的数据库(如Postgres或MySQL),您可以使用.query()模型的方法来访问底层适配器并运行本机命令.这是一个例子:

buyItem: function(req, res) {
  try {
    // Start the transaction
    User.query("BEGIN", function(err) {
      if (err) {throw new Error(err);}
      // Find the user
      User.findOne(req.param("userId").exec(function(err, user) {
        if (err) {throw new Error(err);}
        // Update the user balance
        user.balance = user.balance - req.param("itemCost");
        // Save the user
        user.save(function(err) {
          if (err) {throw new Error(err);}
          // Commit the transaction
          User.query("COMMIT", function(err) {
            if (err) {throw new Error(err);}
            // Display the updated user
            res.json(user);
          });
        });
      });
    });
  } 
  // If there are any problems, roll back the transaction
  catch(e) {
    User.query("ROLLBACK", function(err) {
      // The rollback failed--Catastrophic error!
      if (err) {return res.serverError(err);}
      // Return the error that resulted in the rollback
      return res.serverError(e);
    });
  }
}
Run Code Online (Sandbox Code Playgroud)