mouchin777
mouchin777

Reputation: 1588

How to save a fetched JSON in a variable [node-fetch]

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 )

Upvotes: 0

Views: 3606

Answers (1)

1565986223
1565986223

Reputation: 6718

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.

Upvotes: 3

Related Questions