Home How to choose which function is called first in Node Js
Reply: 2

How to choose which function is called first in Node Js

iNukeLaPeste
1#
iNukeLaPeste Published in 2018-02-13 13:57:49Z

I am currently using an Ether package and NodeJS to learn a few things.

Here is my code:

var ethers = require('ethers');
var providers = require('ethers').providers;

var infuraProvider = new providers.InfuraProvider(process.argv[3]);

infuraProvider.getBlockNumber().then(function(blockNumber) {
  console.log("Current block number: " + blockNumber);
});

infuraProvider.getGasPrice().then(function(gasPrice) {
  console.log("Current gas price: " + gasPrice.toString());
});

It basically gets the network from my argument, and then get blockNumber and gasPrice. So if run this, here is what I get:

Current block number: 5083149
Current gas price: 8000000000

Which is what I want. But sometimes, it gives the gas price BEFORE the block number, like that:

Current gas price: 8000000000
Current block number: 5083149

How can I edit my code so it always give the block number first? I tried to play with the .then keyword, but didn't manage to make it work.

Thanks

Terry Lennox
2#
Terry Lennox Reply to 2018-02-13 14:10:47Z

You can do something like:

infuraProvider.getBlockNumber().then(function(blockNumber) {
    console.log("Current block number: " + blockNumber);
    infuraProvider.getGasPrice().then(function(gasPrice) {
        console.log("Current gas price: " + gasPrice.toString()); 
    });
});

Otherwise you're basically racing the two Promises and it may not be deterministic which one goes first.

Or, in an async function, you can do:

var printDetails = async function()
{
    let blockNumber = await infuraProvider.getBlockNumber();
    console.log("Current block number: " + blockNumber);
    let gasPrice = await infuraProvider.getGasPrice();
    console.log("Current gas price: " + gasPrice.toString());
}

printDetails();
Rahul Sharma
3#
Rahul Sharma Reply to 2018-02-13 14:05:54Z

Try this

infuraProvider.getBlockNumber().then(function(blockNumber) {
  console.log("Current block number: " + blockNumber);
  return infuraProvider.getGasPrice();
}).then(function(gasPrice) {
  console.log("Current gas price: " + gasPrice.toString());
});
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.323274 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO