FrontendDeveloper.in

ECMAScript question detail

Promises

A promise is an object which represent the eventual completion or failure of an asynchronous operation.

It is in one of these states:

pending: Represents initial state, neither fulfilled nor rejected. fulfilled: Indicates that the operation is completed successfully. rejected: Indicates that the operation is failed.

A promise is said to be settled if it is either fulfilled or rejected, but not pending. The instance methods promise.then(), promise.catch(), and promise.finally() are used to associate further action with a promise that becomes settled. And these methods also return a newly generated promise object, which can optionally be used for chaining.

Screenshot

The promise chaining structure would be as below,

const promise = new Promise(function(resolve, reject) {
setTimeout(() => resolve(1), 1000);
});

promise.then(function(result) {
console.log(result); // 1

return result * 2;
}).then(function(result) {
console.log(result); // 2

return result * 3;
}).then(function(result) {
console.log(result); // 6

return result * 4;
}).catch(function(error){
console.log(error);
});
Back to all ECMAScript questions
Get LinkedIn Premium at Rs 399