Promise관련 질문 하나 드리겠습니다.

function test(){
    (async () => {
        await new Promise(() => console.log("1"));
    })();
    console.log("2");
}
test();
// 결과
1
2

이 코드를 실행시키면 1 다음에 2가 출력됩니다.
처음에 생각하기로는 Promise는 콜백 큐에 들어가게되니 2가 먼저찍히고 2가 찍히겠구나 생각했습니다.
왜 생각과 다르게 나왔는지 생각해봐서 나온 결론이

즉시 실행 함수가 호출 스택에 들어가고, 함수 안에 있는 Promise는 즉시 실행 함수 안에 아무런 실행 할 것이 없어 호출 스택이 비었으니 이벤트 루프가 콜백 큐에서 Promise를 가져와서 실행 시켜 1이 출력됩니다. 이후 호출 스택에 console.log(“2”)가 들어가 2가 출력됩니다.

인데 이렇게 해석하는게 맞을까요?

Promiseawait 키워드나 .then()으로 동기화하지 않는 이상 여러 Promise를 실행할 경우 순서는 보장되지 않습니다. 예시로 주신 코드의 경우, console.log가 그렇게 시간 잡아먹는 작업이 아니라서 console.log("2") 가 실행되기도 전에 완료가 된 듯합니다. async () => {...}부분에 좀 오래 걸리는 작업을 넣어두시면 자연스럽게

2
1

이 나올 겁니다.

1개의 좋아요

저도 궁금해서 좀 알아봤는데, Promise에 인자로 전달된 함수 () => console.log("1")Promise가 생성될 때 실행되네요.

A function to be executed by the constructor, during the process of constructing the new Promise object. (Promise() constructor - JavaScript | MDN)

function test(){
  const promise1 = (async () => {
    const promise2 = new Promise((resolve) => {
      console.log('1');
      setTimeout(() => {
        console.log('3');
        resolve('4');
      });
    });
    console.log('promise2 before await:');
    console.log(promise2);

    await promise2;
    console.log('promise2 after await:');
    console.log(promise2);
  })();

  console.log('promise1:');
  console.log(promise1);

  console.log('2');
}

test();


// 출력값:
// 1
// promise2 before await:
// Promise { <pending> }
// promise1:
// Promise { <pending> }
// 2
// 3
// promise2 after await:
// Promise { '4' }
3개의 좋아요