1

Objective: Assign a global variable to the first indexed address returned in web3.eth.getAccounts(). I want this so I can use it in the rest of my code and simply reference a variable.

Problem: Promises. There's something I'm not getting.

Two ways I've tried this:

1) async + await

var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
const getAccounts = async () => {
   const accounts = await web3.eth.getAccounts();
   return accounts;
};
let acct = getAccount()[0];
console.log('The first account is: ' + acct);

2) .then()

    var Web3 = require('web3');
    var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
    let acct = web3.eth.getAccounts().then(data => {return data[0];});
    console.log('The first account is: ' + acct);

Neither seem to be working for me, and must be doing something wrong. Best I can return is "Promise { pending }"

Can anyone help explain how I can use the result of a promise elsewhere in my code?

1 Answer 1

3

In both cases for your let, you're assigning a promise again.

If you can run the rest of your code in an async function, the easiest way is:

async function() {
    ...
    let acct = (await web3.eth.getAccounts())[0];
    ... you other code here ...
}

If you want to run the rest of your code outside of an async function, you'll have to delay the execution of the rest, until the promise is fulfilled.

Your Answer

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

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