0
var Tx = require('ethereumjs-tx').Transaction
var Web3 = require('web3')
web3 = new Web3('https://mainnet.infura.io/v3/a47d55XXXXXXXXXXX')
var balance1 = web3.eth.getBalance('0x0539B9c9C886e93778542XXXC64cb5EAfB902b1')
console.log(balance1)

When I run this in the command prompt:

C:\Users\HP\path
node file.js
Promise { <pending> }

Why does this happen all the time? I have never executed a transaction because all of them are "pending"

2 Answers 2

3

web3.eth.getBalance makes an RPC (remote procedure call) to the Ethereum Node process which the given web3 instance is connected to (https://mainnet.infura.io in your case).

This process will send a response, while your process can continue running and wait for that response elsewhere in your code.

So web3.eth.getBalance returns Promise object, which you need to resolve at some point in the execution of your program.

For example, if you want to do this immediately, then you can run that piece of code inside an async function and await for web3.eth.getBalance to complete:

async func() {
    var balance1 = await web3.eth.getBalance('0x0539B9c9C886e93778542XXXC64cb5EAfB902b1');
    console.log(balance1);
}
2

An asynchronous function returns a promise, web3.eth.getBalance(...) is such a function. You have to await the result, there are two ways to do this:

async function myAsyncFunction() {
  // your code
  console.log(await balance1)
}

alternatively use the old style:

// your code
balance1.then((balance) => {
  console.log(balance);
});

Promise: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise async:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.