我正在使用 web3 版本 1.0.0-beta.27
,其中对区 block 链的所有访问都将是异步的,显然这开启了竞争条件的可能性,即:
var Web3 = require("web3");
// connect to etherum blockchain
var ether_port = 'http://localhost:8545'
var web3 = new Web3(new Web3.providers.HttpProvider(ether_port));
// this is how we set the value, note there is the possiblity of race condidtions here
var accounts = []
web3.eth.getAccounts().then(function(accts){
console.log("printing account: ", accts)
accounts = accts
})
// observe race condition
console.log("assert race condition: ", accounts[0])
上面的最后一行是人为的,它是为了证明我想在评估后使用accounts
。也就是说,最终我想从前端 express.js
Web 应用程序甚至移动应用程序修改/读取区 block 链,因此为了严格起见,node.js
中有哪些常用工具可以确保竞争条件永远不会发生?这些工具存在吗?如果不是,有哪些常见做法。我也是 node.js
的新手。
最佳答案
一个想法是不要尝试直接存储数据,因为由于异步结果的不确定性,尝试访问数据的代码不知道数据何时有效。因此,您可以存储 Promise 和任何想要访问数据的代码,只需在 Promise 上使用 .then()/.catch()
即可。无论异步时间如何,这都将始终有效。如果数据已经存在,.then()
处理程序将被快速调用。如果数据尚未到达,则调用者将在数据到达时收到通知。
let accountDataPromise = web3.eth.getAccounts().then(function(accts){
console.log("printing account: ", accts)
return accts;
});
// then, elsewhere in the code
accountDataPromise.then(accts => {
// use accts here
}).catch(err => {
// error getting accts data
});
仅供引用,将 .then()
处理程序中的数据分配给您希望在 Promise 链之外的其他代码中通常使用的更高范围的变量几乎总是麻烦代码的标志 - 不要这样做。这是因为 promise 链之外的其他代码不知道该数据何时有效或无效。
关于javascript - 正确的 node.js 抽象可防止访问以太坊区 block 链时的竞争条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48154852/