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 )
4
  • 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. Commented Apr 25, 2019 at 11:06
  • Why are using this befor jsonBlock which is defined with var at the begining of the file? Commented Apr 25, 2019 at 11:06
  • 2
    Possible duplicate of How do I return the response from an asynchronous call? Commented Apr 25, 2019 at 11:07
  • Try using .then(res => jsonBlocks = res.Json()) Commented Apr 25, 2019 at 11:08

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.