Skip to content

Instantly share code, notes, and snippets.

@mmmunk
Created September 3, 2020 11:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmmunk/39e33e9ebde5e51e6f9987f6dc5b4588 to your computer and use it in GitHub Desktop.
Save mmmunk/39e33e9ebde5e51e6f9987f6dc5b4588 to your computer and use it in GitHub Desktop.
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
result_func(data);
})
.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
alert(err);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment