Data access outside of function - Javascript

José Carlos 886 Reputation points
2024-03-28T15:29:44.3033333+00:00

Hi

I have the following code in javascript:


var dadosJSON = '';

async function lerArquivoJSON(caminhoDoArquivo) {
  const resposta = await fetch(caminhoDoArquivo);
  const dados = await resposta.json();
  return dados;
}

async function main() {
  dadosJSON = await lerArquivoJSON('dados1.json');

  console.log(dadosJSON[4].time, dadosJSON[4].arquivo, dadosJSON[4].pais);
}

main();

console.log(dadosJSON[4].time, dadosJSON[4].arquivo, dadosJSON[4].pais);

Inside the main() function I can show the data in console.log. Why can't I access the data outside of the function?

Tks.

Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
4,611 questions
JavaScript API
JavaScript API
An Office service that supports add-ins to interact with objects in Office client applications.
867 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 112.1K Reputation points
    2024-03-28T18:31:25.5466667+00:00

    Try using then:

    . . .
    
    main().then( _ =>
    {
        console.log( dadosJSON[4].time, dadosJSON[4].arquivo, dadosJSON[4].pais );
    } );
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful