Search code examples
jsonecmascript-6fetchlet

how to update a variable in es6 inside a fetch function?


I have this code below:

let courses = '';

fetch(link)
.then(function(response) {
  return response.json();
}).then(function(json) {
  courses = json;
}).catch(function(ex) {
  console.log('parsing failed', ex);
});

Using console.log(courses) prints out ''.

How do I set it to the retrieved json?


Solution

  • The fetch method is asynchronous, essentially, you will only have access to the json content in the courses variable after the fetch promise resolves. Try doing the following:

    function synchronousCode(courses) {
      console.log('courses', courses); // output json courses
    }
    
    fetch(link)
    .then(function(response) {
      return response.json();
    })
    .then(synchronousCode)
    .catch(function(ex) {
      console.log('parsing failed', ex);
    });
    

    One of the benefits of using the Fetch API is that you can neatly chain your methods instead of just having one "synchronousCode" function. Here's an example:

    function asynchronouslyAnalyze(courses) {
      return new Promise(function(resolve, reject) {
        setTimeout(function () { resolve(courses) }, 1000);
      });
    }
    
    function parse(courses) {
      // do something with courses
      return courses;
    }
    
    function print(courses) {
      console.log('courses', courses); // output courses json
    }
    
    function toJSON(response) {
      return response.json();
    }
    
    fetch(link)
    .then(toJSON)
    .then(asynchronouslyAnalyze)
    .then(parse)
    .then(print)
    .catch(function(ex) {
      console.log('parsing failed', ex);
    });
    

    I hope that helps!