2.4 async/await 분석

박창진·2022년 4월 16일
0

async/await => promise로 바꾸어보기

async function a() {
	const a = await 1; // await -> then
    console.log('a', a);
    console.log('hello);
    await null;
    const b = await Promise.resolve(1);
    console.log('b', b);
    return b;
}
==> Promise로 바꾸면...100%는 아니지만 이런 식으로 된다
Promise.resolve(1)
	.then((a) => {
    	console.log('a', a);
    	console.log('hello);
        return null;
    })
    .then(() => {
    	return Promise.resolve(1);
    })
    .then((b) => {
    	console.log('b', b);
        return b;
    })
    
a().then((result) => {
	console.log(result);
}).then((result2) => {
	console.log(result2);
});

* async/await는 오른쪽 부터 분석하자
* promise의 then의 부분은 await와 다음 await까지 코드라고 생각하자

async/await 코드 분석

async function a() {
	console.log('jin');
	const a = await 1; // await -> then
    console.log('a', a);
    console.log('hello');
    await null;
    const b = await Promise.resolve(5);
    console.log('b', b);
    return b;
}

console.log('spear');

a().then((result) => {
	console.log(result);
}).then((result2) => {
	console.log(result2);
});
console.log('park');

* 결과: spear, jin, park, a 1, hello, b 5, 5, undefined

그림을 보면서 같이 분석해보자

  • anonymouse가 호출이 되고, console.log('spear')가 실행이되고 사라진다.
  • a함수가 호출이되고, then함수 2개가 백그라운드에 저장된다.
  • a함수 안에 console.log('jin')이 실행되고 사라지고, await함수 3개는는 백그라운드에 저장된다.
  • console.log('park')이 실행되고 사라진다.
  • 호출 스택이 비어지면 await함수와, then함수는 순서대로 마이크로 큐로 이동해진다.
  • 호출 스택이 비었으니 await(1)부터 호출 스택으로 이동해진다.
  • console.log('a', a)가 호출되고, 사라지고, console.log('hello')이 호출되고 사라진다.
  • await(1)함수가 종료가 되면, await(null)이 호출스택으로 넘어간다.
  • 그 다음 함수도 차례대로 호출스택으로 넘어가고 종료된다.

await를 남발하지 말자

async function a() {
	await delayP(3000);
    await delayP(6000);
    await delayP(9000);
}
=> 우리는 3초, 6초, 9초후의 함수가 실행되기를 원했지만...
다음 같이 await를 남발하면, 3초, 9초, 18초의 결과를 얻게 된다

async function b() {
	const p1 = delayP(3000);
    const p2 = delayP(6000);
    await Promise.all([p1, p2]);
    await delayP(9000);
}
=> 다음 같이 하면 우리가 원하는 3초, 6초, 9초의 결과를 얻을 수 있다
* Promise.all등 메소드를 사용하면 동시에 실행이 가능하다
* promise는 기본적으로 바로 실행이 되고, 결과 값이 나오고, 결과값을 사용한다
* 하지만 우리는 실행이되고, 결과 값이 나오기 전에 결과값을 사용하기를 원한다.
* 그때 사용하는 메소드가 then, await인 것이다
profile
I'm SpearJin

0개의 댓글