Footnotes

  1. async 함수를 실행할때 리턴과 관련된 예제로 해당 기능을 설명해주고 있다. ↩

  2. reject 는 Error 객체로 — 문자열로 거부하면 스택 트레이스가 남지 않는다. ↩

  3. try/catch문을 사용할 경우 결과값을 다시 변수에 할당 해야 하는데 그럴 경우 문법적 간결함이 애매해 지기 때문에 .catch로 체이닝해서 다음 구문에 조건문으로 처리하는 방법을 알려주고 있다. ↩

  4. 페이지 로딩 중 unmount 될때 이미지 요청 취소 기능을 위해 찾아봤다. ↩

#2

콜백 → Promise → async/await

// 콜백
fetchData(() => {
  processData(() => {
    displayData()
  })
})

// Promise 체인
fetchData().then(processData).then(displayData)

// async/await
async function main() {
  const data = await fetchData()
  const processed = await processData(data)
  await displayData(processed)
}

Promise는 모나드처럼 동작 — then 은 콜백이 Promise 를 돌려주면 풀어서 잇는다(flatMap). 값을 돌려주면 감싼다(map). 한 메서드가 둘 다 해서 Promise<Promise<T>> 는 만들어지지 않는다.1


Footnotes

  1. Promise.prototype.then() — MDN: “The value returned from then() is resolved in the same way as Promise.resolve(). This means thenable objects are supported, and if the return value is not a promise, it’s implicitly wrapped in a Promise and then resolved.” ↩

#536