Skip to content

Instantly share code, notes, and snippets.

@webpapaya
Created November 11, 2020 16:27
Show Gist options
  • Save webpapaya/eec97e47843d1da477cc7199bec4bdc0 to your computer and use it in GitHub Desktop.
Save webpapaya/eec97e47843d1da477cc7199bec4bdc0 to your computer and use it in GitHub Desktop.
code from Frontend Development lecture (2020-11-11)
const callbackFetch = (url, callback) => {
// ....
}
const promiseFetch = (url) => {
return new Promise((resolve, reject) => {
callbackFetch(url, (result) => {
if (result.error) { reject(result) }
else { resolve(result) }
})
})
}
// Use wrapped promise
function promiseFetchBestFriendsAddress() {
return promiseFetch('/api/currentUser')
.then((currentUser) => promiseFetch(`/api/user/${currentUser.id}/bestFriend`))
.then((bestFriend) => promiseFetch(`/api/user/${bestFriend.id}/address`))
.then((addressOfBestFriend) => console.log(addressOfBestFriend))
}
// Convert wrapped promise to async function
async function asyncFetchBestFriendsAddress() {
const currentUser = await promiseFetch('/api/currentUser')
const bestFriend = await promiseFetch(`/api/user/${currentUser.id}/bestFriend`)
const bestFriendsAddress = await promiseFetch(`/api/user/${bestFriend.id}/address`)
console.log(bestFriendsAddress)
}
const questions = [
{ whatever: '...' },
{ whatever: '...' },
{ whatever: '...' },
{ whatever: '...' },
]
async function getQuestions() {
// delay
return questions
}
const callbackFetch = (url, callback) => {
// ....
}
const promiseFetch = (url) => {
return new Promise((resolve) => {
callbackFetch(url, resolve)
})
}
function myBestFriendsAddress() {
return promiseFetch('/api/currentUser')
.then((currentUser) => promiseFetch(`/api/user/${currentUser.id}/bestFriend`))
.then((bestFriend) => promiseFetch(`/api/user/${bestFriend.id}/address`))
}
function renderBestFriendsAddressInHTMLPromise () {
myBestFriendsAddress()
.then((address) => {
document.innerHTML(JSON.stringify(address))
})
}
async function renderBestFriendsAddressInHTMLAsync () {
const address = await myBestFriendsAddress()
document.innerHTML(JSON.stringify(address))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment