Skip to content

Instantly share code, notes, and snippets.

@Kcko
Last active March 29, 2024 08:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kcko/7ebe8e8db2ddcca561682f4fcd996a4f to your computer and use it in GitHub Desktop.
Save Kcko/7ebe8e8db2ddcca561682f4fcd996a4f to your computer and use it in GitHub Desktop.
function getUserInfo() {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject('request exception')
}, 1000)
})
}
// 1) Try-catch
async function loggedIn() {
try {
let userInfo = await getUserInfo()
// Execution interrupt
let pageInfo = await getPageInfo(userInfo?.userId)
} catch(e) {
console.warn(e)
}
}
// 2 direct catch
async function loggedIn() {
let userInfo = await getUserInfo().catch(e => console.warn(e))
// Execution continues, userInfo might be undefined
if (!userInfo) return
let pageInfo = await getPageInfo(userInfo?.userId)
}
// 3 direct catch with handle
async function loggedIn() {
let userInfo = await getUserInfo().catch(e => {
console.warn(e)
return Promise.reject(e)
})
// Execution interrupt
let pageInfo = await getPageInfo(userInfo?.userId)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment