-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
You even tried to use the keyword
return
to return, for example,data.docs[0]
? Another question that might help you understand that subject is this: How to assign a Promise result to a variable?.– Luiz Felipe