'Web3 code working in terminal but not my IDE

I am very new to web3 and relatively new to JavaScript. The following code returns undefined for the variable accounts.

Here is my code:

const Web3= require('web3');
var web3 = new Web3("HTTP://127.0.0.1:7545");
var accounts; 
web3.eth.getAccounts().then(acc=>{accounts = acc});
console.log(accounts);

The code works completely in the terminal, printing out the list of accounts. However, it says undefined when I run it in the IDE. I have tried multiple things, such as even declaring a new function to be called from the web3.eth.getAccounts() as a callback, setting the account variable. Nothing works.



Solution 1:[1]

The getAccounts() function returns a promise which resolves later than the console.log, so before the accounts variable has been set.

You can either use the accounts variable after it's been set (watch out for the callback hell)

web3.eth.getAccounts().then(acc => {
    accounts = acc;
    console.log(accounts);
});

or use the await expression in an async function

async function run() {
    var accounts;
    accounts = await web3.eth.getAccounts();
    console.log(accounts);
}

run();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Petr Hejda