티스토리 뷰
반응형
연속적인 async 함수의 호출을 함수형으로 처리하기 위해 async한 pipe 함수를 다음과 같이 구현할 수 있다.
(async function main() {
const results = await pipeAsync(
getTargetAsync,
pickAlias,
getInfoAsync,
getFriendsAsync
)("injuk");
console.log(results);
/* 실행 결과
[
{ id: '222', name: 'two', bf: 'ingnoh' },
{ id: '333', name: 'three', bf: 'ingnoh' },
{ id: '444', name: 'four', bf: 'ingnoh' }
]
*/
})();
function pipeAsync(...asyncFun) {
return function (initValue) {
return asyncFun.reduce(async (promise, currAsyncFun) => {
const resolvedValue = await promise;
return currAsyncFun(resolvedValue);
}, initValue);
};
}
async function getTargetAsync(name) {
return Promise.resolve({
name,
age: 3,
alias: "ingnoh",
});
}
function pickAlias(target) {
return Reflect.get(target, 'alias');
}
async function getInfoAsync(alias) {
return Promise.resolve({
id: "111",
name: alias,
});
}
async function getFriendsAsync({ name: bf }) {
return Promise.resolve([
{ id: "222", name: "two", bf },
{ id: "333", name: "three", bf },
{ id: "444", name: "four", bf },
]);
}
그런데 pickAlias는 async한 함수가 아니므로 Promise가 아닌 값을 반환하지만, pipeAsync에서는 await promise; 에서 pickAlias의 결과에 대해 await을 시도한다.
확인 결과 async 함수에서 Promise가 아닌 값을 반환하면 Promise로 래핑되듯, Promise가 아닌 값에 대한 await 역시 resolve 된 Promise로 값을 한 번 감싸 처리한다고 한다.
궁금한 건 일단 모질라 문서부터 찾아봐야할 것 같다.
참고
'Dev. > javascript' 카테고리의 다른 글
[Prettier] 임의의 폴더에만 prettier 적용하기 (1) | 2023.12.04 |
---|---|
[JS] 파일 이름으로 사용할 수 없는 문자만 인코딩하기 (0) | 2023.02.08 |
[JS] function call, apply, bind 차이 (0) | 2022.12.02 |
[JS] 클래스에 async getter 작성하기 (0) | 2022.10.07 |
[JS] 값이 null 또는 undefined인지 확인하기 (0) | 2022.10.04 |
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- JPA
- javascript
- Git
- Java
- IntelliJ
- react
- Puppeteer
- AWS
- kotlin
- Node.js
- 코딩테스트
- Spring Cloud Config
- AWS IoT
- postgresql
- RancherDesktop
- Docker
- eureka
- terraform
- Vault
- spring boot
- hashicorp
- shell
- Linux
- etc
- jQuery
- pgloader
- JEST
- Database
- mysql
- Gradle
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함