Promise, async, await

TIL 2020.12.21

Joo Hee Paige Kim
2 min readDec 21, 2020

JavaScript is synchronous and execute the code block by order after hoisting(var, function declaration)

Asynchronous does not know the order of operations. In order to handle that, we can use callback, promise, async await.

Callback has a pitfall of readability and difficulty of debugging and can end up as callback hell.

Promise came out in ES6 in order to fix callback but also has a problem of readability by having .then continuously, which can be ‘promise hell’

Async Await is promise-based, which has a good readability(ES8)

  • Event loop checks stack and if it is empty, it sends first item(callback)inside queue to stack
  • In JS, cannot render if there is a code in stack and has to wait until stack is clear.
  • Rendering has higher priority over callback so every 16 milliseconds, it is going to queue render, wait til stack is clear before it can actually do the render.
  • While doing slow synchronous loop, render is blocked so cannot select text in screen, and etc.
  • But if it is asynchronous, it is still blocked while we queue up but it clears out relatively quick because we give the render a chance between each element since it was queued up asynchronously to jump in there and do the render

Promise

  • a JavaScript object for asynchronous operation

State

  1. pending (while operation)
  2. fulfilled
  3. rejected

Producer vs Consumer

Producer

  • when new Promise is created, the executor runs automatically!

Consumers: then, catch, finally

Promise Chaining

  • promise chain는 같은 객체를 리턴하지 않고 항상 다른 promise를 리턴하게 됨

Error Handling

then(onFulfilled, onRejected) 두개의 parameters를 넘길 수 있음

onFulfilled = then에서 성공했을 때 실행하는 함수

onRejected = then에서 예외처리해 줄 수 있는 함수

async & await

  • clear style of using promise
  • promise를 위에 더 간편한 API를 제공하는 것 => Syntactic Sugar

async

키워드를 쓰면 바로 함수앞에 쓰면 코드 블럭이 promise가 되어버림

async 함수의 리턴은 promise의 resolve와 동일하다고 할 수 있음

await

async 함수 안에서만 사용 가능

promise를 기달릴 수 있는 아이(fulfilled나 rejected 될 때까지 기다려줌)

Error Handling

reference:

https://www.youtube.com/channel/UC_4u-bXaba7yrRz_6x6kb_w

https://www.youtube.com/channel/UC9hWQRe4QrUivXN3VO2iuMA

--

--