Skip to content

Instantly share code, notes, and snippets.

@mmmunk
Last active October 13, 2024 11:36
Show Gist options
  • 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
async function fetchData(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Network response was not ok (status ${response.status})`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching data:', error);
throw error; // Re-throw the error to allow the caller to handle it
}
}
// Usage example:
fetchData('https://api.example.com/data')
.then(data => {
// Process the fetched data here
console.log(data);
})
.catch(error => {
// Handle errors here
console.error('Error:', error);
});
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
console.log(data);
});
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