Search code examples
javascriptnode.jsnode-fetch

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 )

Solution

  • 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.