Skip to content

Instantly share code, notes, and snippets.

@mmmunk

mmmunk/fetch-ex.js

Created Sep 3, 2020
Embed
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
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
You can’t perform that action at this time.