Javascript promise chaining
Created By: chatGPT
In JavaScript, Promise chaining is a technique that allows multiple async operations to be executed sequentially. This empowers developers to coordinate tasks that may depend on each other. When a Promise is returned from a function, you can use the
.then()
method to execute the next operation once the previous one is settled.function firstTask() {
return new Promise((resolve) => {
setTimeout(() => {
console.log('First task completed');
resolve('Data from first task');
}, 1000);
});
}
function secondTask(dataFromFirst) {
return new Promise((resolve) => {
setTimeout(() => {
console.log('Second task completed with:', dataFromFirst);
resolve('Data from second task');
}, 1000);
});
}
firstTask()
.then(secondTask)
.then((dataFromSecond) => {
console.log('All tasks completed with:', dataFromSecond);
});
When chaining Promises, each
.then()
block can return a new Promise. The next .then()
will receive the resolved value from the previous Promise. This creates a clean and readable flow as you handle asynchronous operations sequentially.function fetchData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve('Fetched data');
}, 1000);
});
}
fetchData()
.then((data) => {
console.log(data);
return 'Transforming data';
})
.then((transformedData) => {
console.log(transformedData);
return 'Final result';
})
.then((final) => {
console.log(final);
});
Additionally, if any Promise in the chain is rejected, you can handle the error by attaching a
.catch()
at the end of the chain. This ensures that you can manage errors effectively without disrupting the flow of the program.function errorProneTask() {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject('Error occurred');
}, 1000);
});
}
errorProneTask()
.then(() => {
console.log('This will not run');
})
.catch((error) => {
console.error('Caught an error:', error);
});