javascript async await의 원리?
2022-10-23 오후 7:14:42

개요
event-loop과 비동기처리 관련해서
조사하다보니 async, await 문법이 어떤 원리로
동작하는지 궁금해져서 조사해보기로 했다.
이 게시글은 javascript callback, promise, generator, async-await에 대한
기본 개념은 알고 있는 사람을 기준으로 작성됨
1. 탄생배경
1-1. callback 지옥
예전에는 front-end 작업을 할때 단순한 화면 작업이 대부분이였지만,
요즘은 규모나 난이도가 많이 달라졌다.
특정 작업을 수행한 다음 동기적으로 실행할 코드가 있는 경우
callback 함수를 넘겨주는 방식을 사용했는데
가독성이 매우 좋지 않은 중첩 구조가 많이 발생하여
아래 이미지와 같은 짤방까지 만들어질 정도였다.
1-2. Promise, generator의 탄생
front-end 뿐 아니라 node.js의 영역이 커지게 되면서
다양한 규모의 비동기 제어를 표준 API를 통해 깔끔하게 제어하고자 하는
니즈가 있었고,
ES6(2015)스펙에 정식으로 Promise
와 generator
가 추가되었다.
Promise에 대한 개념은 자바스크립트 개발자라면 익히 할고 있을것이라 생각하고,
generator의 경우 링크에서 잘 설명해주고 있으니 참고 바란다.
위 두가지(Promise, generator)문법을 가지고 async-await의 역할이 가능해졌다.
그러나 generator 역시 가독성이 좋지는 않았다. ( 생소한 문법 )
C#에서는 async, await의 문법으로 매우 간단하게 처리할 수 있었는데
많은 자바스크립트 개발자들이 async-await가
하루빨리 표준스펙이 되길 기다렸다고 한다.
2. async, await
그리하여 async, await 문법은 ES8(2017)스펙에 추가되게 된다.
처음에는 이를 지원하는 브라우저가 많지 않아
babel을 통해 Promise와 generator를 조합해서 사용하는 형태로
변환되어 실행되었다. ( 참고 )
MDN의 async function문서를 보면 현재 대부분의 브라우저들이
모두 async 문법을 지원하고 있다.
문서를 살펴보면
An async function is a function declared with the
async
keyword, and theawait
keyword is permitted within it. Theasync
andawait
keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains. Async functions may also be defined as expressions.
최상단에 위처럼 기재되어있다.
개발자가 async 문법을 사용할때는 Promise와 generator가 합쳐진
개념으로 편하게 사용하면 된다.
다만 예전에는 babel을 통해 javascript(Promise, generator)로 직접 핸들링했다면
지금은 v8이 async문법을 뒤에서(under the hood)
잘 처리해주도록 바뀌게 되었다. ( v8 블로그, ECMA )
해당 게시글은
promise와 async 퍼포먼스 개선에 대한 내용이다.
처음 async 문법이 나왔을때 promise를 사용하는 것보다는 퍼포먼스가 느렸다가 개선되었나보다.
아래 영상은 해당 내용에 대한 V8팀의 발표 영상이다. ( 꼭 보는걸 추천 )
게시글 중간쯔음 아래 예시와 함께 설명이 작성되어있다.
( 영상에서는 약 9분 9초
부분 )
async function foo(v) { const w = await v; return w; }
When called, it wraps the parameter v into a promise and suspends execution of the async function until that promise is resolved. Once that happens, execution of the function resumes and w gets assigned the value of the fulfilled promise. This value is then returned from the async function.
await
under the hoodFirst of all, V8 marks this function as resumable, which means that execution can be suspended and later resumed (at await points). Then it creates the so-called implicit_promise, which is the promise that is returned when you invoke the async function, and that eventually resolves to the value produced by the async function.
상세한 원리는 첨부된 발표 영상과,
v8 블로그에 이미지와 함께 설명이 잘 작성 되어있으니,
확인해보기 바란다. ( 발표영상이 이해가 더 잘되는것같다 )
출처
https://meetup.toast.com/posts/73
https://velog.io/@proshy/async-await-%EB%8F%99%EC%9E%91%EC%9B%90%EB%A6%AC
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/async_function.
https://v8.dev/blog/fast-async
https://tc39.es/ecma262/#await