Promise, async, await
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
- pending (while operation)
Producer vs Consumer
- when new Promise is created, the executor runs automatically!
Consumers: then, catch, finally
- promise chain는 같은 객체를 리턴하지 않고 항상 다른 promise를 리턴하게 됨
then(onFulfilled, onRejected) 두개의 parameters를 넘길 수 있음
onFulfilled = then에서 성공했을 때 실행하는 함수
onRejected = then에서 예외처리해 줄 수 있는 함수
async & await
- clear style of using promise
- promise를 위에 더 간편한 API를 제공하는 것 => Syntactic Sugar
키워드를 쓰면 바로 함수앞에 쓰면 코드 블럭이 promise가 되어버림
async 함수의 리턴은 promise의 resolve와 동일하다고 할 수 있음
async 함수 안에서만 사용 가능
promise를 기달릴 수 있는 아이(fulfilled나 rejected 될 때까지 기다려줌)