Skip to content

Instantly share code, notes, and snippets.

@prof3ssorSt3v3
Last active December 6, 2024 16:58
Show Gist options
  • Save prof3ssorSt3v3/4e91a1fe44bff775331971d6720129d3 to your computer and use it in GitHub Desktop.
Save prof3ssorSt3v3/4e91a1fe44bff775331971d6720129d3 to your computer and use it in GitHub Desktop.
Promises discussion file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Promises</title>
<script>
document.addEventListener('DOMContentLoaded', init);
function init() {
//html loaded
fetchWithAwait();
fetchWithThen();
}
async function fetchWithAwait() {
//make a fake fetch call with await
try {
let resp = await notFetch();
if (!resp.ok) throw new Error('notFetch did not fetch?');
let data = await resp.json(); // or .blob() or .text()
//now use the data
} catch (err) {
//handle the error here
console.warn(err.message);
// if (err instanceof FetchError) {
if (err.constructor.name == 'FetchError') {
//specific error type
} else {
//generic error
}
//Also tell the user there was a problem
}
}
function fetchWithThen() {
//make a fake fetch call using then()
notFetch()
.then(handleTheResponse)
.then(buildHTML)
.then(userFeedback)
.catch((err) => {
//handle the error types here
});
}
function userFeedback() {
console.log('success');
}
function handleTheResponse(resp) {
console.log(resp);
if (!resp.ok) throw new Error('notFetch did not fetch?');
return resp.json();
}
function buildHTML(data) {
//
}
//TODO: How to clone a Response object to use in multiple places
function notFetch(url) {
//pretend to do a fetch call
return new Promise((resolve, reject) => {
setTimeout(() => {
let obj = { id: 123, name: 'bob' };
let file = new File([JSON.stringify(obj)], 'data.json', { type: 'application/json' });
let resp = new Response(file, {
status: 200,
headers: {
'content-type': 'application/json',
'content-length': file.size,
},
});
resolve(resp);
}, 1234);
});
}
</script>
</head>
<body></body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment