我有一个使用Ganache在http://127.0.0.1:7545上运行的本地区块链。区块链上有8个区块,没有一个是挂起的。
我在nodejs中编写了一个脚本,使用web3从块中获取数据,但由于某些原因,它无法工作。
脚本是这样的:
Web3 = require('Web3')
const web3 = new Web3('http://127.0.0.1:7545')
console.log(web3.eth.getBlockNumber())
var block = web3.eth.getBlock('latest')
console.log(block)
var firstblock = web3.eth.getBlock(0)
console.log(firstblock)
console.log(firstblock.hash)这是脚本执行输出
>node script.js
Promise { <pending> }
Promise { <pending> }
Promise { <pending> }
undefined发布于 2020-06-26 21:13:39
getBlock方法始终返回promise。如果要访问块对象,则应添加.then()。所以它应该是这样的:
Web3 = require('Web3')
const web3 = new Web3('http://127.0.0.1:7545')
web3.eth.getBlockNumber().then(console.log)
var block = web3.eth.getBlock('latest')
block.then(console.log)
var firstblock = web3.eth.getBlock(0)
firstblock.then(console.log)
firstblock.then( block => console.log(block.hash))https://stackoverflow.com/questions/62595221
复制相似问题