본문 바로가기

개인공부 기록/node.js

[JavaScript] Promise (1)

Promise 란?

▶ 현재에는 없지만 가까운 미래에는 있을 수도 있는 어떤 데이터에 대한 접근방법

Promise 를 생성해보자

function returnPromise() {
  return new Promise((resolve, reject) => {  } );
}

Promise 객체는 new 키워드와 생성자를 사용해 만듭니다. 생성자(resolve, reject)는 매개변수로 "실행 함수"를 받습니다. 이 함수는 매개 변수로 두 가지 함수를 받아야 하는데, 첫 번째 함수(resolve)는 비동기 작업을 성공적으로 완료해 결과를 값으로 반환할 때 호출해야 하고, 두 번째 함수(reject)는 작업이 실패하여 오류의 원인을 반환할 때 호출하면 됩니다. 두 번째 함수는 주로 오류 객체를 받습니다. 

 

다음은 Promise에 위 내용을 적용한 코드입니다.

function devide(num1, num2) {
  return new Promise((resolve, reject) => {
    if (num2 === 0) reject(new Error("not devide by 0"));
    else resolve(num1 / num2);
  });
}

정상적인 인자를 넘겨 divide 함수를 호출해 Promise 객체를 얻은 후 결과값을 출력해보겠습니다.

devide(8, 2)
  .then((result) => console.log("성공:", result))
  .catch((error) => console.log("실패:", error));
  
  // 성공: 4

비정상적인 인자를 넘기는 경우에는 catch 메서드가 호출 될 것을 예상해 볼 수 있을 것 같습니다.

 

Promise 체인

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then((response) => response.json())
  .then((post) => console.log("post:", post))
  .catch((error) => console.log("error:", error));

 

then() 과 cathc() 메서드는 또다른 Promise 객체를 리턴하는데요, 이 Promise 객체는 인자로 넘긴 콜백 함수의 리턴 값을 다시 then()과 catch()에 접근할 수 있도록 해줍니다. 위 예시에서는 응답결과와 더불어 응답전문의 json 형태로 출력하고 싶은 경우 then() 메서드를 추가로 연결해주면 됩니다.

 

 

 

REFERENCE

 

 

[자바스크립트] 비동기 처리 2부 - Promise

Engineering Blog by Dale Seo

www.daleseo.com

 

Recent Posts
Popular Posts
Recent Comments