콜백 → 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
-
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.” ↩