Promises Chaining
Promises/Async/Await: Promises Chaining
What is promise chaining in JavaScript?
View Answer:
new Promise(function (resolve, reject) {
setTimeout(() => resolve(1), 1000); // (*)
})
.then(function (result) {
// (**)
console.log(result); // 1
return result * 2;
})
.then(function (result) {
// (***)
console.log(result); // 2
return result * 2;
})
.then(function (result) {
console.log(result); // 4
return result * 2;
});
How does promise chaining help in error handling?
View Answer:
function performAsyncTask1() {
return new Promise((resolve, reject) => {
// Asynchronous task 1
});
}
function performAsyncTask2(resultFromTask1) {
return new Promise((resolve, reject) => {
// Asynchronous task 2
});
}
performAsyncTask1()
.then(resultFromTask1 => performAsyncTask2(resultFromTask1))
.then(resultFromTask2 => console.log(resultFromTask2))
.catch(error => console.error('An error occurred:', error)); // error handling in a catch
What is a common mistake made by beginners in JavaScript concerning the chaining of promises?
View Answer:
let promise = new Promise(function (resolve, reject) {
setTimeout(() => resolve(1), 1000);
});
promise.then(function (result) {
console.log(result); // 1
return result * 2;
});
promise.then(function (result) {
console.log(result); // 1
return result * 2;
});
promise.then(function (result) {
console.log(result); // 1
return result * 2;
});
An example of breaking the chain of Promises is using the promise.then, in an individual invocation, subscribe to a promise.
Can you briefly explain the benefits of returning a new promise in JavaScript?
View Answer:
new Promise(function (resolve, reject) {
setTimeout(() => resolve(1), 3000);
})
.then(function (result) {
console.log(result); // 1
// Returning a Promise
return new Promise((resolve, reject) => {
// (*)
setTimeout(() => resolve(result * 2), 2000);
});
})
.then(function (result) {
// (**)
console.log(result); // 2
return new Promise((resolve, reject) => {
setTimeout(() => resolve(result * 2), 1000);
});
})
.then(function (result) {
console.log(result); // 4
});
Can you briefly explain what a thenable is in JavaScript?
View Answer:
class Thenable {
constructor(num) {
this.num = num;
}
then(resolve, reject) {
console.log(resolve); // function() { native code }
// resolve with this.num * 2 after the 1 second
setTimeout(() => resolve(this.num * 2), 1000); // (**)
}
}
new Promise((resolve) => resolve(1))
.then((result) => {
return new Thenable(result); // (*)
})
.then(console.log); // shows 2 after 1000ms
What happens if an error occurs in a chain of promises?
View Answer:
firstPromise()
.then(result1 => secondPromise(result1))
.then(result2 => thirdPromise(result2))
.catch(error => console.error('An error occurred:', error));
In this example:
If
firstPromiserejects or throws an error,secondPromiseandthirdPromisewill not be executed. Instead, the control is passed to the catch() method, and the error message fromfirstPromisewill be logged.If
firstPromiseresolves butsecondPromiserejects or throws an error,thirdPromisewill not be executed. Instead, the control is passed to the catch() method, and the error message fromsecondPromisewill be logged.If both
firstPromiseandsecondPromiseresolve butthirdPromiserejects or throws an error, the control is passed to the catch() method, and the error message fromthirdPromisewill be logged.
In each case, the catch() method handles the error, preventing it from causing a complete halt of the script execution or from resulting in an unhandled promise rejection, which could lead to undefined behavior or application crash. It's also good practice to always have a catch() at the end of your promise chain to ensure that all possible errors are handled appropriately.
How can you return a value from a chained promise in order to use it in subsequent code?
View Answer:
myPromise
.then(value => {
console.log(value); // Logs: Hello, JavaScript!
return value + ' How are you?';
})
.then(newValue => {
console.log(newValue); // Logs: Hello, JavaScript! How are you?
})
.catch(error => {
console.error('An error occurred:', error);
});
What is the role of the finally() method in promise chaining?
View Answer:
Can a catch() method be followed by a then() method in promise chaining?
View Answer:
doSomething()
.then(result => {
console.log(`Success: ${result}`);
})
.catch(error => {
console.error(`Error: ${error}`);
})
.then(() => {
console.log('This is always called');
});
How do you handle multiple asynchronous operations with different error-handling using promise chaining?
View Answer:
firstPromise()
.then(result1 => {
// Use result1
return secondPromise(result1);
})
.catch(error => {
console.error('An error occurred in firstPromise:', error);
})
.then(result2 => {
// Use result2
return thirdPromise(result2);
})
.catch(error => {
console.error('An error occurred in secondPromise:', error);
})
.then(result3 => {
// Use result3
})
.catch(error => {
console.error('An error occurred in thirdPromise:', error);
});
In this example:
If
firstPromisefails, its error will be caught in the first.catch()block and the subsequent.then()and.catch()blocks will not be executed.If
secondPromisefails, its error will be caught in the second.catch()block and the last.then()and.catch()block will not be executed.If
thirdPromisefails, its error will be caught in the last.catch()block.
Keep in mind that in this structure, if a promise fails, the following promises will not be executed because a rejected promise will immediately lead the control flow to the nearest .catch() block.
This method provides granular control over error handling for each promise, allowing you to handle each error in a different manner if needed.
This way of handling errors in promises is not very common because usually we want to execute all asynchronous tasks and handle all the errors in a centralized .catch() block. But it can be useful in some specific cases.
Can you describe how promise chaining helps in avoiding callback hell?
View Answer:
How do you transform callback-based functions into promises for chaining?
View Answer:
function callbackFunction(data, callback) {
// ... some async operation
callback(error, result);
}
// transforming the above function into a promise-based function
function promiseFunction(data) {
return new Promise((resolve, reject) => {
callbackFunction(data, (error, result) => {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
}