async/await 고찰

cornpip·2023년 6월 11일
0

node.js

목록 보기
1/2
post-thumbnail

async/await 고찰

const test = (who, time) => {
    return (
        new Promise((resolve, reject) => {
            setTimeout(() => {
                console.log(who, time);
                resolve(who);
            }, time)
        })
    )
}

async function running_test() {
    const d = [1, 2, 3, 4];
    const dd = [];
    // d.forEach(async (v) => {
    //     dd.push(await test(v, 1000));
    // })
    for(let i of d){
        await test(i, 1000);
    }
    console.log(dd);
    const a = await test(dd, 1000);
    console.log("@@@@@@", a);
    const b = await test(a, 250);
    console.log("@@@@@@", b);
}

running_test();

맥락 = context = scope 암튼 해당 함수지역

await는 속해있는 맥락에서 비동기 기다려주고 그동안 다음 맥락이 진행된다.
A맥락 안에 forEach, map같은 B맥락이 있고 거기서 await를 쓴다면 B맥락 멈추고 A맥락 진행

근데 결과적으로 보면
B맥락에서 await를 걸었을 때 A맥락으로 돌아와 진행하다가 A에서 B의 결과값이 필요한 것에 await만 잘 건다면 비동기는 순서대로 진행되므로 B의 await가 먼저 진행되고 결과값을 받아 A가 진행된다.

그래서 정상작동하긴 할텐데 잘못하면 놓치는 부분 생기기 쉬워보이므로

웬만하면 이중 삼중 들어가는 맥락에서 await활용하지 말고 await반복은 for문으로 해당 맥락에서 해결하자.

profile
https://cornpip.tistory.com 티스토리로 이전했습니다!

0개의 댓글