본문 바로가기
프론트엔드/Vue.js

비동기 예외 처리(then, catch, finally)

by step 1 2021. 9. 10.
반응형

Promise 공식 문서

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Promise#%EB%A9%94%EC%84%9C%EB%93%9C

 

Promise - JavaScript | MDN

Promise 객체는 비동기 작업이 맞이할 미래의 완료 또는 실패와 그 결과 값을 나타냅니다.

developer.mozilla.org

 

resolve 메서드를 이용한 비동기 처리 방법

function a() {
  return new Promise ((resolve) => {
    setTimeout(() => {
      console.log('A')
      resolve()
    }, 1000)
  })
}
function b() {
  return new Promise ((resolve) => {
    setTimeout(() => {
      console.log('B')
      resolve()
    }, 1000)
  })
}
function c() {
  return new Promise ((resolve) => {
    setTimeout(() => {
      console.log('C')
      resolve()
    }, 1000)
  })
}
function d() {
  return new Promise ((resolve) => {
    setTimeout(() => {
      console.log('D')
      resolve()
    }, 1000)
  })
}
function test() {
  // const promise = a()
  // promise.then(() => {
  //   console.log('B')
  // })
  
  // a().then(() => {
  //   b().then(() => {
  //     c().then(() => {
  //       d().then(() => {
  //         console.log('Done!')
  //       })
  //     })
  //   })
  // })

  // a().then(() => {
  //   return b()
  // }).then(() => {
  //   return c()
  // }).then(() => {
  //   return d()
  // }).then(() => {
  //   console.log('Done!!!')
  // })

  a()
    .then(() => b())
    .then(() => c())
    .then(() => d())
    .then(() => {
      console.log('Done!!!!')
    })
}

test()

브라우저 확인

 

reject를 이용하여 예외처리를 진행하는 방법

function a(number) {
  return new Promise ((resolve, reject) => {
    if (number > 4) {
      // then 메소드가 실행되지 않도록 설정
      reject();
      // 변수가 4이상일 경우 아래 코드가 실행되지 않도록 설정
      return
    }
    setTimeout(() => {
      console.log('A')
      resolve()
    }, 1000)
  })
}

// function test() {
//   a(7)
//     .then(() => {
//       console.log('Resolve!')
//     })
//     .catch(() => {
//       console.log('Reject!')
//     })
//     .finally(() => {
//       console.log('Done!')
//     })
// }

// async, await를 이용하여 예외처리를 하는 방법
async function test() {
  try {
    await a(8)
    console.log('Resolve!')
  } catch (error) {
    console.log('Reject')
  } finally {
    console.log('Done!')
  }
  
}
test()

브라우저 확인

반응형