티스토리 뷰

반응형

연속적인 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로 값을 한 번 감싸 처리한다고 한다.

궁금한 건 일단 모질라 문서부터 찾아봐야할 것 같다.

참고

 

await - JavaScript | MDN

Promise 혹은 기다릴 어떤 값입니다.

developer.mozilla.org

 

댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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 29 30 31
글 보관함