/ Gists / Catching async/await
On gists

Catching async/await

JavaScript

how-to-catching.js Raw #

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)
}