async / await (revised)

효딩딩·2022년 10월 24일
0

1. async 란?

  • function 앞에 async를 붙이면 해당 함수는 promise 를 반환
  • async가 붙은 함수는 반드시 promise를 반환하고, promise가 아닌 것은 promise로 감싸 반환
  • async가 들어있는 함수가 들어있을 경우에 안에 있는 로직이 다 끝날 때까지 프로그램이 종료가 되지 않음

2. await 란?

  • await는 '기다리다’라는 뜻을 가진 영단어
  • await는 말 그대로 프라미스가 처리될 때까지 함수 실행을 기다림
  • 중간에 한 줄 한 줄 내려가면서 await이 있을 경우 비동기 처리가 끝날 때까지 기다렸다가 정상적으로 resolve 되면 resolve에 넘어온 인자(값)을 넘겨서 밑으로 계속 이어서 진행함
  • promise가 처리되길 기다리는 동안엔 엔진이 다른 일(다른 스크립트를 실행, 이벤트 처리 등)을 할 수 있기 때문에, CPU 리소스가 낭비되지 않음
  • await을 사용하는 경우 항상 async 함수 안에서 사용되어야 함

출처:
https://start.jcolemorrison.com/5-tips-and-thoughts-on-async-await-functions/
https://blog.naver.com/sleekydz86/222900494429
https://blog.naver.com/ares132/222862278087
https://ko.javascript.info/async-await


(영문 해석)

1. What is async?

An async function is a function declared with the async keyword, and the await keyword is permitted within it. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.

A Promise which will be resolved with the value returned by the async function, or rejected with an exception thrown from, or uncaught within, the async function.

2. What is await?

Async functions can contain zero or more await expressions. Await expressions make promise-returning functions behave as though they're synchronous by suspending execution until the returned promise is fulfilled or rejected. The resolved value of the promise is treated as the return value of the await expression.

Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.

Source:
https://www.w3schools.com/js/js_async.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

profile
어제보다 나은 나의 코딩지식

0개의 댓글