Return Array Item created with asynchronous function

Asked

Viewed 84 times

-4

With an asynchronous function I am creating an array to receive data from an API. By giving console.log(data) I can correctly return all the data in the array, but by trying to return only one item, as in console.log(data[0]) is returned as Undefined. How can I return only one item?

var dados = [];

async function getContent() {
  try {
    const response = await fetch('http://localhost:3001/api/products?page=1');
    const data = await response.json();

    for (var i = 0; i < data.docs.length; i++) {
      dados[i]  
        = {
          'key': i + 1,
        'nome': "" + data.docs[i].name + "",
        'hs': data.docs[i].hs
      }
    }

  } catch (error) {
    console.log('error');
  }
}

getContent();

console.log(dados); // retorna os valores do array (como na imagem).

console.log(dados[0]); //retorna undefined
console.log(dados[1]); //retorna undefined

Retorno no console

1 answer

1


Two wrong ones are making a right in your code.

When you do console.log(dados), there will be nothing inside that array called dados. You are only able to view the filled array because of the way the developer console works.

The console.log(dados) does not print the array immediately on the console, it just passes the array reference, and when you try to view this data, the console will fetch the array and print the current content.

For this very reason you cannot visualize the console.log(dados[0]) and the console.log(dados[1]): the array is not even populated at that point, and additionally the indices 0 and 1 did not exist, so even after your array has been filled in, the console will not be able to fetch those references.

What you need to do is wait for the resolution of your asynchronous function getContent before printing the dados:

var dados = [];

async function getContent() {
  try {
    const response = await fetch('http://localhost:3001/api/products?page=1');
    const data = await response.json();

    for (var i = 0; i < data.docs.length; i++) {
      dados[i]  
        = {
          'key': i + 1,
        'nome': "" + data.docs[i].name + "",
        'hs': data.docs[i].hs
      }
    }

  } catch (error) {
    console.log('error');
  }
}

async function main() {
    await getContent();

    console.log(dados);
    console.log(dados[0]);
    console.log(dados[1]);
}

main();

Preferably, you should also generate and return the array dados in function getContent instead of declaring it as global.

  • 3

    Instead of using a global variable like dados to "pass" the data of getContent for main, it would not simply be easier to return the function data getContent using the return? That kind of thing seems like a anti-pattern... In addition, by using global variables in this way, state is being shared indiscriminately, which can provide racing conditions.

  • 1

    @Luizfelipe, yes, that’s what I commented on in the last line. The example I created was following the logic of the user to keep the same reasoning.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.