Skip to Content
Suffering builds character

5. Promise 후속 처리

비동기 작업 결과에 따른 후속 처리

resolve / reject 콜백에 의해 프로미스를 통한 비동기 작업 상태가 변화하게 되면 후속 처리를 수행할 코드를 작성해야 함
Ex. pending → fulfilled

Promise 객체는 개발자가 후속 작업을 작성할 수 있는 별도의 함수를 제공함

후속 처리

  • 비동기 작업 성공 시, 응답 결과 값 추출, 화면에 렌더링 등
  • 작업 실패 시, 에러 메시지에 따른 분기, 로깅 등

1. then(), catch(), finally()

1-1. then(callback)

비동기 처리가 성공하여 resolve 콜백이 호출되었을 경우 동작
실제 동작하는 것은 then()이 아닌 then(callback) 함수의 인수로 전달된 콜백 함수

promise.js
const promise = new Promise(executor); promise .then((response) => console.log(`응답 결과: ${response}`)); // 응답 결과: some data

1-2. catch(callback)

비동기 처리가 실패하여 reject 콜백이 호출되었을 경우 동작하는 함수

promise.js
const promise = new Promise(executor); promise .then((response) => console.log(`응답 결과: ${response}`)) .catch((error) => console.error(`error: ${error}`)); // error: 응답 실패

1-3. finally(callback)

비동기 처리 성공/실패 여부와 상관없이 마지막에 한 번은 무조건 동작하도록 보장되는 함수

promise.js
const promise = new Promise(executor); promise .then((response) => console.log(`응답 결과: ${response}`)) .catch((error) => console.error(`error: ${error}`)); .finally(() => console.log('요청 수행 완료')); // 응답 결과: some data or error: 응답 실패 // 요청 수행 완료(무조건 한 번은 동작)
Last updated on