0

I have the following code , which logs the json if I use a console.log, but I want to save it in the jsonBlocks variable. But it won't work. I guess its because of async stuff, but I cant find a way to solve it.

var jsonBlocks;


fetch('https://myurl')
    .then(res => res.text())
    .then(body => this.jsonBlocks = body )
mouchin777
  • 1,428
  • 1
  • 31
  • 59
  • Whatever you want to do with the data, you have to do it *after* the async function has finished. You're probably trying to do this too early, while the fetch is still running. We need to see more code to provide help though. –  Apr 25 '19 at 11:06
  • Why are using `this` befor `jsonBlock` which is defined with var at the begining of the file? – DSCH Apr 25 '19 at 11:06
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –  Apr 25 '19 at 11:07
  • Try using .then(res => jsonBlocks = res.Json()) – Martin M Apr 25 '19 at 11:08

1 Answers1

3

You can use async..await for the particular piece of code like:

async function getBlock() {
  let jsonBlocks;
  try {
    var response = await fetch('https://myurl');
    jsonBlocks = await response.text();
    console.log(jsonBlocks)
  } catch (e) {
    // handle error
    console.error(e)
  }
}

getBlock()

If you return anything from getBlock, it'll be wrapped in Promise.

1565986223
  • 6,420
  • 2
  • 20
  • 33