Chaining Promises
by dshilkret
HTML
<div>
This example shows how to chain promises. The first fetchData promise fetches some data, and then processData processes the fetched data. The chaining ensures that the second promise waits for the first one to complete.
</div>
JavaScript
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => resolve("Data fetched"), 1000);
});
const processData = data => new Promise((resolve, reject) => {
setTimeout(() => resolve(`${data} and processed`), 1000);
});
fetchData
.then(result => processData(result))
.then(finalResult => console.log(finalResult))
.catch(error => console.error(error));