-
Apologies for my basic understanding of Promises, but I tried and these code doesn't work and I tried searching for solutions for understanding how should I consume Promises, and none worked. var ethers = require("ethers");
var url = "wss://bsc-ws-node.nariox.org:443";
const provider = new ethers.providers.WebSocketProvider(url);
const blockNumber = async function() {
return await provider.getBlockNumber();
}
console.log(blockNumber()); This outputs var ethers = require("ethers");
var url = "wss://bsc-ws-node.nariox.org:443";
const provider = new ethers.providers.WebSocketProvider(url);
async function blockNumber() {
const blockNumber = await provider.getBlockNumber();
return blockNumber();
}
blockNumber().then(data => {console.log(data)}); This outputs `` nothing on the console! Just as a sanity check: >./geth attach wss://bsc-ws-node.nariox.org:443
Welcome to the Geth JavaScript console!
instance: Geth/v1.1.0-beta-032970b2/linux-amd64/go1.16.4
at block: 9380974 (Thu Jul 22 2021 21:39:44 GMT+0800 (+08))
modules: eth:1.0 net:1.0 rpc:1.0 web3:1.0
To exit, press ctrl-d
> eth.blockNumber
9380976
> exit |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
You should check out this documentation to learn more about Promises. A lot of ethers returns Promises, so becoming more familiar with Promises will help you a lot, as well as for JavaScript programming in general. You can use something akin to an async IIFE: const ethers = require("ethers");
const url = "wss://bsc-ws-node.nariox.org:443";
const provider = new ethers.providers.WebSocketProvider(url);
// async IIFE
(async function() {
const blockNumber = await provider.getBlockNumber();
console.log(blockNumber);
})(); One other quick suggestion, avoid using Hope that helps. :) |
Beta Was this translation helpful? Give feedback.
You should check out this documentation to learn more about Promises. A lot of ethers returns Promises, so becoming more familiar with Promises will help you a lot, as well as for JavaScript programming in general.
You can use something akin to an async IIFE:
One other quick suggestion, avoid using
var
and instead use let and const. They will save a lot of headaches down the road. :)Hope that helps. :)