Web3.js getBlock() 将所有块都显示为待处理
Web3.js getBlock() is giving me all blocks as pending
我在 http://127.0.0.1:7545 上有一个使用 Ganache 的本地区块链 运行。区块链上有 8 个区块,其中 none 个待处理。
我在 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
getBlock
方法总是returns一个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))
我在 http://127.0.0.1:7545 上有一个使用 Ganache 的本地区块链 运行。区块链上有 8 个区块,其中 none 个待处理。
我在 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
getBlock
方法总是returns一个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))