javascript - 正确的 node.js 抽象可防止访问以太坊区 block 链时的竞争条件

标签 javascript node.js ethereum race-condition web3js

我正在使用 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/

相关文章:

node.js - 在 Ubuntu 上使用 fs.writeFileSync 得到错误 : EACCES: permission denied

cryptography - 带有 ed25519 曲线签名的 BIP44

javascript - React 不更新数组内对象的属性

javascript - 在 ES6/TS 中通过 mutate 将对象设置为 null 以匹配 Set 中的条件

javascript - 复制正常的NodeJS错误打印行为

python - 如何使用 Infura 监听 Python 中的事件(2019 年末)?

javascript - 如何通过HardHat获取底层合约地址的私钥?

javascript - 确定 Canvas 网格的单元格 x 和 y

javascript - Ajax 调用似乎无法识别我的文件

node.js - 创建 geddy 应用程序后 geddy 命令中断