Skip to content

Instantly share code, notes, and snippets.

Created September 3, 2020 11:25
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Example use of Javascript Fetch
function call_api(url, args, rsp_json, result_func) {
// Start the fetch chain of promises
fetch(url, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(args)
.then(rsp => {
// rsp.ok true if rsp.status is 200-299
if (rsp.ok) {
// Return a new promise to next .then section
return rsp_json ? rsp.json() : rsp.text();
} else {
// Return a rejected promise and execution ends in .catch
return Promise.reject('API HTTP Error ' + rsp.status + ': ' + rsp.statusText);
.then(data => {
// Use the data returned from previous .then
.catch(err => {
// We end here if fetch fails (fx connection error) but NOT if server answers with any rsp.status
// We also end here if we return a Promise.reject in .then
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment