프로미스 체인이란?
- 순차적으로 비동기를 처리하기 위한 비동기 처리 방법론이다.
- then으로 다음 실행하는 순서를 보장할 수 있다.
const promise = new Promise();
promise
.then(() => {
})
.then(() => {
});
프로미스 체인을 이용한 정제
- 프로미스 체인을 이용해서 두개의 Promise의 결과값을 배열로 가지고 있는
pending
상태의 프로미스로 정제할 수 있다.
- Promise.all의 형태로 사용할 수 있으며 순서를 보장할 수 있다.
const data1 = {
name: "YHJ",
};
const data2 = {
name: "HGD",
};
const promise = (data) => new Promise((resovle, reject) => resovle(data));
const promiseChaining = () => {
return promise(data1).then((res1) => {
return promise(data2).then((res2) => {
return [res1, res2];
});
});
};
promiseChaining().then((res) => console.log(res));
프로미스 체인 함수 만들기
- 위의 코드에서는 단점이 존재하는데 바로 유동적이지 못하다는 단점을 가지고 있다.
- 함수로 파라미터의 개수만큼 정제하는 코드를 만들어 재사용성을 증가시킬 수 있다.
- 초기값인
Promise.resolve([])
의 역할은 처음 acc의 then 메소드를 사용하기 위한 초기 설정이다.
- 재귀함수를 사용하거나 reduce 메소드를 사용하여 구현이 가능하다.
const data1 = {
name: "YHJ",
};
const data2 = {
name: "HGD",
};
const promise = (data) => new Promise((resovle, reject) => resovle(data));
const promiseChainingReduce = (...arr) => {
return arr.reduce((acc, curr) => {
const next = acc.then((accRes) => {
const currRes = promise(curr).then((res) => [...accRes, res]);
return currRes;
});
return next;
}, Promise.resolve([]));
};
promiseChainingReduce(data1, data2).then((res) => console.log(res));
const promiseChaingRecursion = (init, ...arr) => {
const item = arr.shift();
const next = init.then((prev) => {
const curr = promise(item).then((res) => [...prev, res]);
return curr;
});
if (arr.length) return promiseChaingRecursion(next, ...arr);
return next;
};
promiseChaingRecursion(Promise.resolve([]), data1, data2).then((res) =>
console.log(res)
);