0

There's my code:

   fetch(data)
    .then(blob => blob.json())
    .then(newData => array.push(newData))
let be = array[0].id;

I'd like to access my array data, but I end up with undefined and I don't know why.
After reloading page

However it works just fine in console.
Working good with console.log

I've been reading all over the internet for hours, but I can't seem to understand why does it work like that.

Lovs
  • 351
  • 2
  • 7

1 Answers1

1

fetch run asynchronously so, you can do something like this.

let array = [];
let be = '';

fetch(data)
 .then(blob => blob.json())
 .then(newData => {
    array.push(newData);
    be = array[0].id;
 });

As soon as you call your fetch method, while it wait's response from the server or from wherever you are trying to get the information, the i/o doesn't stop and starts executing the rest of the code while waiting the response from server.

Adeel Imran
  • 13,166
  • 8
  • 62
  • 77
  • It does work indeed, thank you. (I'd upvote but i'm noob in terms of overstack and don't know how to do it ) – Lovs Feb 11 '18 at 19:18