비동기 처리

외부 리소스를 가져오는 시간을 기다리지 않고 다음 소스코드를 실행하는 비동기 처리는 매우 유용합니다. 예전에는 이 비동기 처리를 하는 부분은 콜백 함수로 다루었었습니다. 하지만 비동기 처리로 받은 외부 리소스로 또 다른 외부 리소스를 가져와야하는 경우에는 코드가 매우 보기 흉해집니다. 이제 이러한 코드가 생기지 않게 프라미스를 사용해봅시다.

 

프라미스

프미스는 콜백 함수를 인수로 받는 대신에 성공과 실패에 대응하는 메서드를 사용합니다. 여러 개의 비동기 프라미스를 연결하기 때문에 코드가 보기 좋습니다. 프라미스는 비동기 작업이 성공하거나 총족된 경우 then() 메서드에 결과를 넘겨줍니다. 비동기 작업에 실패하거나 거부되는 경우에는 프라미스가 catch() 메서드를 호출합니다. then()과 catch() 메서드에는 모두 함수를 인수로 전달합니다. 이 두 메소드에 인수로 전달되는 함수에는 비동기 작업의 결과인 응답만이 인수로 전달 됩니다.

 

프라미스는 두 개의 인수 resolve와 reject()를 전달받습니다. resolve()는 코드가 의도대로 동작했을 때 실행됩니다. resolve()가 호출되면 then() 메서드에 전달된 함수가 실행됩니다.

new Promise((resolve, reject) => {
  //비동기 처리
  setTimeout(() => {
    //결과 반환
    resolve({
      data: "data",
    });
  }, 1000);
})
  .then((response) => {
    console.log(response);
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve({
          ...response,
          data2: "data2",
        });
      }, 1000);
    });
  })
  .then((response) => {
    console.log(response);
  })
  .catch((response) => {
    console.log(response);
  });

 

화살표 함수와 프로미스를 적극 이용해 봅시다.

function p1() {
  return new Promise((resolve, reject) => {
    //비동기 처리
    setTimeout(() => {
      //결과 반환
      resolve({
        data: "data",
      });
    }, 1000);
  });
}

function p2(response) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve({
        ...response,
        data2: "data2",
      });
    }, 1000);
  });
}

function p3(response) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve({
        ...response,
        data3: "data3",
      });
    }, 1000);
  });
}

p1()
  .then((response) => p2(response))
  .then((response) => p3(response))
  .then((response) => console.log(response))
  .catch((response) => console.log(response));
블로그 이미지

_김은찬

두번 다시는 꺾이지 않으리

,