have seen similar post before, but can seam to get anything working. I am trying to pull block data (mostly all transactions) from a range of blocks (startBlock-endBlock) but keep getting errors or the function checks out but i return "undefined"
Using a function I found here just to grab transaction counts by block range (working up to full list) :Common useful JavaScript snippets for geth
function checkTransactionCount(startBlockNumber, endBlockNumber) {
console.log("Searching for non-zero transaction counts between blocks " + startBlockNumber + " and " + endBlockNumber);
for (var i = startBlockNumber; i <= endBlockNumber; i++) {
var block = web3.eth.getBlock(i);
if (block != null) {
if (block.transactions != null && block.transactions.length != 0) {
console.log("Block #" + i + " has " + block.transactions + " transactions")
}
}
}
}
but get "undefined" when i run checkTransactionCount(startBlockNumber, endBlockNumber).
pretty new to web3.js, any help is appreciated
Best Answer
web3.eth.getBlock(i)
is an asynchronous function, you should either use a callback or async / await. Because you are not waiting for the result, you getundefined
simply because there is no result (yet).Here is a version using the callback :
Or as stated above, you could use async / await like so :
EDIT : Here is an example using async / await returning an array with the transactions hash that are present between
startBlockNumber
andendBlockNumber
: