web3.eth – Fixing web3.eth.getBlock(“latest”) Returning No Object

javascripttransactionsweb3js

I am trying to get the numbers of transactions in a rinkeby testnet in the last block

I wrote the following code

var Web3 = require('web3');

const Project_ID_Infura = 'write your own Infura ID';

const apiKey = 'https://rinkeby.infura.io/v3/' + Project_ID_Infura;

const web3 = new Web3(new Web3.providers.HttpProvider(apiKey));

var block = web3.eth.getBlock('latest');

console.log(Object.values(block));

Where as you can see it is empty! I want to get the transaction field of this block. How may I do so?

Best Answer

It seems that there are changes when using the web3 library everytime. At the time of writing. It seems that the block variable is a promise!

What is meant by promise? Promises in JavaScript represent processes that are already happening, which can be chained with callback functions as described here.

So it seems that the only viable way to get how many transactions were in the last block is by adding the below line to the code above.

block.then(x=> {return x.transactions.length});

This gave me the return I want but I was unable to store it as a variable. I am still learning how to do so but thought of sharing half of the solution.

Note: A nice video explaining promise in JavaScript is available here

Related Topic