将 BN 转换为数字
Convert BN to number
在 truffle 控制台中,我正在执行以下语句,
result = token.balanceOf(accounts[1])
这条语句returns输出如下。
<BN: 8ac7230489e80000>
按照建议 here,我正在尝试使用 toNumber()
和 toString
。但是我收到以下错误。
result = token.balanceOf(accounts[1])
result.toString()
output: '[object Promise]'
result.toNumber()
TypeError: result.toNumber is not a function
帮我解决这个问题。
根据输出结果,您似乎得到了一个 Promise。
在运行“result.toString()”命令的那一刻-它仍然是一个尚未实现的承诺。
正如@Saddy 在评论中提到的,您需要等待 promise 实现,然后才能对其值使用 toString() 方法。
您应该在该方法之前添加“await”。
请参阅 truffle 文档中的示例 (https://www.trufflesuite.com/docs/truffle/quickstart):
Check the metacoin balance of the account that deployed the contract:
truffle(development)> let balance = await instance.getBalance(accounts[0])
truffle(development)> balance.toNumber()
就像@Saddy 提到的那样,您可以await
承诺解决,如@Ofir 所示,或者如下所示。
truffle(development)> await instance.getBalance(accounts[0]).then(b => { return b.toNumber() })
在 truffle 控制台中,我正在执行以下语句,
result = token.balanceOf(accounts[1])
这条语句returns输出如下。
<BN: 8ac7230489e80000>
按照建议 here,我正在尝试使用 toNumber()
和 toString
。但是我收到以下错误。
result = token.balanceOf(accounts[1])
result.toString()
output: '[object Promise]'
result.toNumber()
TypeError: result.toNumber is not a function
帮我解决这个问题。
根据输出结果,您似乎得到了一个 Promise。 在运行“result.toString()”命令的那一刻-它仍然是一个尚未实现的承诺。
正如@Saddy 在评论中提到的,您需要等待 promise 实现,然后才能对其值使用 toString() 方法。
您应该在该方法之前添加“await”。
请参阅 truffle 文档中的示例 (https://www.trufflesuite.com/docs/truffle/quickstart):
Check the metacoin balance of the account that deployed the contract:
truffle(development)> let balance = await instance.getBalance(accounts[0])
truffle(development)> balance.toNumber()
就像@Saddy 提到的那样,您可以await
承诺解决,如@Ofir 所示,或者如下所示。
truffle(development)> await instance.getBalance(accounts[0]).then(b => { return b.toNumber() })