[JavaScript] Promise를 이용한 비동기 처리

parkheeddong·2023년 5월 9일

JavaScript

목록 보기
25/26
post-thumbnail


🔔 Promise란?!

Promise는 현재에는 당장 얻을 수는 없지만 가까운 미래에는 얻을 수 있는 어떤 데이터에 접근하기 위한 방법을 제공한다.

당장 원하는 데이터를 얻을 수 없다는 것은 데이터를 얻는데까지 ❗ 지연 시간(delay, latency) ❗이 발생하는 경우를 의미한다!

Example.

Promise 객체를 생성하여 리턴하고, 호출부에서는 리턴받은 Promise 객체에 then() 메서드를 호출하여 결과값을 가지고 실행할 로직을 넘겨준다.

콜백 함수를 통해 비동기 처리와 차이점
= 함수를 호출하면 Promise 타입의 결과값이 리턴된다.
이 결과값을 가지고 다음에 수행할 작업을 진행한다.

findUser(1).then(function (user) {
  console.log("user:", user);
});

function findUser(id) {
  return new Promise(function (resolve) {
    setTimeout(function () {
      console.log("waited 0.1 sec.");
      const user = {
        id: id,
        name: "User" + id,
        email: id + "@test.com",
      };
      resolve(user);
    }, 100);
  });
}

결과

waited 0.1 sec.
user: {id: 1, name: "User1", email: "1@test.com"}


🔔 Promise 생성 방법

✅ 변수에 할당되는 경우
const promise = new Promise(function(resolve, reject) { ... } );
✅ 함수의 리턴값으로 사용되는 경우
function returnPromise() { return new Promise((resolve, reject) => { ... } );}

Promise는 객체는 new 키워드와 생성자로 생성한다.
생성자는 "함수"를 인자로 받고, 함수는 "reslove와 reject"라는 2개의 함수형 파라미터를 가진다.

📌 함수 인자의 바디에서 resolve/reject 함수를 정상 처리, 예외 발생 여부에 따라 호출해준다.
resolve() 함수의 인자로는 미래 시점에 얻게될 결과를 넘겨준다.
➡ reject() 함수의 인자로는 미래 시점에 발생할 예외를 넘겨준다.

function devide(numA, numB) {
  return new Promise((resolve, reject) => {
    if (numB === 0) reject(new Error("Unable to devide by 0."));
    else resolve(numA / numB);
  });
}
devide(8, 2)
  .then((result) => console.log("성공:", result))
  .catch((error) => console.log("실패:", error));
// 성공: 4

devide(8, 0)
  .then((result) => console.log("성공:", result))
  .catch((error) => console.log("실패:", error));
// 실패: Error: Unable to devide by 0.

출력 결과를 통해 정상적인 인자를 넘긴 경우 then() 메서드가 호출되고, 비정상적인 인자를 넘긴 경우 catch() 메서드가 호출되었다는 것을 알 수 있다.



🔔 then과 catch

Promise 객체의 then() 메소드는 결과값을 가지고 수행할 로직을 담은 콜백 함수를 인자로 받는다.

Promise 객체의 catch() 메서드는 예외 처리 로직을 담은 콜백 함수를 인자로 받는다.

Example

REST API를 호출할 때 사용되는 브라우저 내장 함수인 fetch() 함수는 API의 URL을 인자로 받고, 미래 시점에 얻게될 API 호출 결과를 Promise 객체로 리턴한다.

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then((response) => console.log("response:", response))
  .catch((error) => console.log("error:", error));
결과
response: Response {type: "cors", url: "https://jsonplaceholder.typicode.com/posts/1", redirected: false


🔔 Promise의 메서드 체이닝

then()과 catch() 메서드는 또 다른 Promise 객체를 리턴한다.
그리고 이 Promise 객체는 인자로 넘긴 콜백 함수의 리턴값을 다시 then()과 catch() 메서드를 통해 접근할 수 있도록 준다.
즉, then()과 catch() 메서드는 마치 사슬처럼 계속 연결하여 연쇄적으로 호출을 할 수 있다.

Example

이전 섹션의 fetch() 메서드 사용 예제에서 단순히 응답 결과가 아닌 응답 전문을 json 형태로 출력하고 싶은 경우에는 then() 메서드를 추가로 연결해주면 된다.

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

//post: {userId: 1, id: 1, title: "sunt aut facere repellat provident occaecati excepturi optio reprehend

최근에는 Promise를 이용해서 계속해서 메서드 체이닝하는 코딩 스타일은 자바스크립트의 async/await 키워드를 사용하는 방식으로 대체되고 있는 추세이다.

0개의 댓글