Skip to content

Instantly share code, notes, and snippets.

@anthonyalvarez
Last active October 14, 2018 21:44
Show Gist options
  • Select an option

  • Save anthonyalvarez/31ba6dd2ba2baacae87bb647a7c926c0 to your computer and use it in GitHub Desktop.

Select an option

Save anthonyalvarez/31ba6dd2ba2baacae87bb647a7c926c0 to your computer and use it in GitHub Desktop.
Fetch API and Promises

Fetch API and Promises

Semi-colons are placed only inside code blocks and at end of the last promise in the chain.

.then and .catch are similiar to UNIX file pipes process.

Response object methods

  • .text
  • .json
  • .blob

ES5 style

fetch ('/examples//example.json')
    .then(function(response){ 
        return response.json(); 
    })  // do something with the database 
    .catch (function(error){ 
        console.log('Fetch error', error); 
    });

ES6 style

fetch ('/examples/example.json')
    .then(response => { 
        return response.json(); 
    })  // do something with the database 
    .catch (error => { 
        console.log('Fetch error', error); 
    });

Fetch JSON and output

fetch ('/examples/example.json')
  .then(response => { 
    return response.json(); 
  })
  .then(json => { 
    console.log(json); 
  })  
  .catch (error => { 
    console.log('Fetch error', error); 
  });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment