ES6 스터디 정리 : Promise

Llux lux·2022년 4월 19일
0

ES6 스터디

목록 보기
8/21

Promise 란?

자바스크립에서 비동기 처리를 위해 callback 을 사용해 왔으며 비동기 처리를 연속으로 처리하기 위해 중첩되어 처리를 하다보며 복잡도가 증가되었다.
또한 중첩으로 인해 예외처리가 어려워 지는 단점이 있었다.
이 두가지를 해결하기 위해 추가 된 것이 Promise 이다.

const getHello = new Promise((resolve, reject) =>{
    setTimeout(() => {
        resolve("hello"); 
    }, 3000);
});

getHello
    .then((value) => console.log(value))
    .catch(error => console.log(error));

Promise 는 resolve 와 reject 를 가진다.
resolve 는 성공했을 경우 호출하여 값을 전달하는 function 이며
reject 는 실패했을 경우 호출하여 값을 전달하는 function 이다.

Promise 를 실행하고 then 에서는 성공에 대한 이후 액션을 정의하고
catch 에서는 error 를 처리한다.

Chanining Promise(promise 연속 호출)

Promise 를 연속으로 호출한다.
then 을 통해 연속적으로 호출 할 수 있다.
이전에 return 된 값이 다음 then 으로 전달 된다.

const timesTwo = number => {console.log(number * 2); return number * 2};

getHello
    .then(timesTwo)
    .then(timesTwo)
    .then(timesTwo)
    .then(timesTwo)
    .then(timesTwo)
    .then(() =>{throw Error("something is wrong")})
    .then(timesTwo)
    .catch(error => console.log(error));

2 4 8 16 32 64 까지 호출되고 에러가 발생하면서 catch 에서 에러 메시지가 노출된다.
마지막 then 은 실행되지 않는다.

Promise.all()

여러개의 Promise 를 호출하여 모든 처리가 완료 된 후 호출 순서대로 결과를 배열로 리턴해 준다.
중간에 에러가 발생할 경우 모든 결과는 리턴되지 않고 catch에 에러로 처리된다.

const p1 = new Promise((resolve, reject) => {
    setTimeout(resolve, 5000, "First");
})

const p2 = new Promise((resolve, reject) => {
    setTimeout(reject, 1000, "error");
})

const p3 = new Promise((resolve, reject) => {
    setTimeout(resolve, 3000, "Third");
})

const motherPromise = Promise.all([p1, p2, p3]);

motherPromise.then(value => console.log(value))
            .catch(error => console.log(error));

Promise.race()

여러개의 Promise 를 동시에 호출하고 제일 먼저 리터되는 결과 하나를 수신한다.

const p1 = new Promise((resolve, reject) => {
    setTimeout(resolve, 1000, "First");
})

const p2 = new Promise((resolve, reject) => {
    setTimeout(reject, 2000, "error");
})

const p3 = new Promise((resolve, reject) => {
    setTimeout(resolve, 3000, "Third");
})

const motherPromise = Promise.race([p1, p2, p3]);

motherPromise.then(value => console.log(value))
            .catch(error => console.log(error));

finally

finally 를 통해 Promise 가 끝난 후 성공, 실패에 관계 없이 실행되는 함수이다.
이 함수를 통해 최종적으로 실행할 로직을 처리해준다.

const p1 = new Promise((resolve, reject) => {
    setTimeout(resolve, 1000, "First");
}).then(value => console.log(value))
    .finally(() => console.log("finished"));

Real World Promise

실제 Promise 의 사용 사례를 살펴보자
직접 Promise 를 만들어 쓰지 않더라도 Promise 를 리턴하는 함수가 많다.

fetch("https://yts.mx/api/v2/list_movies.json")
    .then(res => res.json()) //.json 함수 역시 promise 를 리턴한다.
    .then(json => console.log(json))
    .catch(e => console.log(e));
profile
하하하

0개의 댓글