Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

218
Visualizações
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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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();
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda