JavaScript Interview Question #81

What is Promise chaining?

Promises, Async/Await, Fetch & Modern JavaScript Mid-Level Intermediate

Quick Interview Answer

Promise chaining connects asynchronous operations by returning a value or another Promise from a then callback. Each subsequent then receives the resolved result of the previous stage.

Detailed Explanation

Promise chaining connects asynchronous operations by returning a value or another Promise from a then callback. Each subsequent then receives the resolved result of the previous stage.

Returning the Promise is important. If an asynchronous operation is started inside then but not returned, the outer chain will not wait for that operation and its rejection may not be handled by the intended chain.

Code Example

fetch("/api/users/1")
    .then(response => response.json())
    .then(user => fetch(`/api/orders?userId=${user.id}`))
    .then(response => response.json())
    .then(orders => console.log(orders))
    .catch(error => console.error(error));