【问题标题】:Web3.js getBlock() is giving me all blocks as pendingWeb3.js getBlock() 将所有块都作为待处理
【发布时间】:2020-10-17 02:00:35
【问题描述】:

我有一个使用 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

【问题讨论】:

    标签: node.js web3 ganache


    【解决方案1】:

    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))
    

    【讨论】:

    • @francesco 你是什么意思?存放在哪里?
    • 在一个 var 中,我试过这样:“ var blockhash=firstblock.then(block => block.hash)” 但它不起作用。抱歉,我第一次处理 Promise 对象
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-19
    • 2019-06-23
    • 1970-01-01
    • 1970-01-01
    • 2018-03-17
    • 2018-01-07
    • 2018-08-18
    相关资源
    最近更新 更多