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