目前我正在开发一种可以进行交易的虚拟货币。我遇到的问题是我不希望同时执行一个用户的多个事务。
下面是一个示例:Tom 和 Bill 都尝试同时向 John 发送 2 美元。我希望我的系统首先为 Tom 完成交易,然后再转移给 Billy 等,而不是同时执行 transact()
函数。
我如何设置这样的系统?
编辑:由于我的代码无论如何都会开源,这里是我当前所做的示例:
//Step 0 - Transaction setup.
var transaction = {
"id": hexit(Math.random().toString().replace(".", "") +
from + to + new Date().getTime() +
Math.random().toString().replace(".", "")),
"from": from,
"to": to,
"amount": amount,
"time": new Date().getTime(),
"coins": [],
"message": validator.escape(message)
};
//LCF.getuser returns the data for the 'coins' field.
var from = LCF.getuser(from, ["coins"]);
//Amount is the amount of coins that the user wants to transact
if(from.coins.length <= amount) {
while(transaction.coins.length < amount) {
collection.update(
{ "username" : from },
{ "$pop": { "coins": 1 } }
);
}
(...)
我需要从 $pop 更新硬币,虽然我可以尝试获取最新文档和之前检索到的文档的差异,但如果在更新时发生另一笔交易,那么我无法知道从用户钱包中 $pop 的硬币。
最佳答案
我尝试使用信号量
,但我不知道如何应用它。
我转向 postgreSQL,这解决了我所有的问题,因为我现在可以使用事务(ROLLBACK、COMMIT 等)。
关于javascript - 在 Node.js 上为用户排队的一种方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22506168/