promise는 JS에서 비동기 처리를 하기 위한 객체이다. 3가지 상태를 가지고 있으며 미래의 성공 혹은 실패에 대한 값을 가지고 있다. 3가지 상태는 다음과 같다.
비동기 함수 func1, func2, func3를 순차적으로 실행하기 위해 아래와 같이 작성할 수 있다.
Promise.resolve(3).then(func1).then(func2).then(func3).then(console.log);
then() 메소드는 promise를 반환한다. 이를 이용하여 체이닝을 하여 표현할 수 있게 된다.
const applyAsync = (p, f) => p.then(f);
const composeAsync = (...af) => af.reduce(applyAsync, Promise.resolve(3));
const f = composeAsync(func1, func2, func3);
applyAsync는 promise와 함수를 받아서 실행하는 함수이다. composeAsync 함수는 함수 배열을 받아서 reduce 메소드를 통해 순차적으로 applyAsync 함수를 실행하여 값을 얻을 수 있게 된다. 이를 통해 func1, func2, func3의 값을 순차적으로 값을 누적할 수 있게 된다.
doSomething(function(result) {
doSomethingElse(result, function(newResult) {
doThirdThing(newResult, function(finalResult) {
console.log('Got the final result: ' + finalResult);
}, failureCallback);
}, failureCallback);
}, failureCallback);
위의 예제처럼 콜백방식은 에러처리가 어렵다. 에러가 전파되기 때문에 failureCallback 이 여러번 호출된다. 하지만 promise를 이용하면 쉽게 처리할 수 있다.
doSomething().then(function(result) {
return doSomethingElse(result);
})
.then(function(newResult) {
return doThirdThing(newResult);
})
.then(function(finalResult) {
console.log('Got the final result: ' + finalResult);
})
.catch(failureCallback);
callback형식으로 비동기 코드를 작성하면 제어권을 callback으로 넘겨서 처리하고, promise는 객체를 바로 받아서 내가 원할 때 then()나 aynsc/await와 같은 방식으로 값을 얻어 주도적으로 처리할 수 있는 것이 장점인 것 같다.