Store values in Array from fetch

0
let arrayDatos = [];

arrayDatos = fetch('url')
 .then(response => response.json())
 .then(posts => return posts)

I'm trying to fill an array with data that returns the fetch function, but asynchronous Javascript I can not fill it. Use promises and I can not find the code either.

Is it possible to do this?

    
asked by Jonathan Ivan Aguero 09.04.2018 в 21:52
source

2 answers

1

The only thing you have to do is:

const arrayDatos = fetch(url).then(res => res.json())

What you are going to store is a promise containing the data obtained through the AJAX request. Keep in mind that fetch returns a promise with the result of the request; therefore, to access the data you must use then :

arrayDatos.then((datos) => {
  // hacer algo con los datos
})

However, if you want to store the data directly from the request; You can use Asynchronous Functions to wait for the result of the promise:

  

Note : To make use of this feature the code where await is called must be in a function marked with async .

const obtenerDatos = async () => {
  const arrayDatos = await fetch(url).then(res => res.json())
  arrayDatos[0] // un valor
  // resto de código
}

It should be clarified that any function marked with async returns a promise regardless of whether something is explicitly returned or not.

    
answered by 09.04.2018 в 22:03
0

Under my point of view you could go one by one the records or data that your fetch returns, then this will be adding something like this in an array:

var data = new Array();
for (i=0; i<dataRetornante.length; i++){
var element={}
element.id=dataRetornante[i]['id'];
element.nombre= dataRetornante[i]['nombre];
data.append(element);
}
console.log(data);//aqui estaria tu resultado en el array data
//dataRetornante es el resultado de tu funcion fetch

luck .. !!

    
answered by 09.04.2018 в 21:59