A promise is an object that represents the completion or failure of an asynchronous task and its resulting value
Syntax: For creating a Promise
let promise = new Promise(function(resolve, reject) {
//Code
});
Promises mainly introduced to avoid multiple callbacks in an asynchronous way. The last story explained the callback function and mentioned the multiple callback code looks very nested leads too hard to understand as well as maintain. Promise helps to overcome the problem. Let see how it works?
The promise object has three states.
pending: Once a promise has been called, it will start with Pending State. The Caller Function Continues the execution.
fulfilled: When a promise object resolved a value, then it is fulfilled.
rejected: When a promise object throws an error, then it is rejected
Creating a Promise Code Pen
A promise is an object so creating an instance with the new keyword. The promise constructor takes one argument, a callback function with two parameters resolve and reject. A promise object represents the completion or failure of an asynchronous task and its resulting value.
Consume the promise object, the object provides the method then to access the resolved value & catch to access the error.
Promise Methods Code Pen
Syntax: Promise.all
Promise.all([promise1, promise2, …])Syntax: Promise.race
Promise.Race([promise1, promise2, …])
Below we are creating few more promises to test the promise methods. Promise p1 is above, p2 and p3 are here.
In the above, we discussed Promise creation, consume and their methods.
How does promise help to overcome the multiple callbacks?
The last story explained the multiple callback function. I am giving the same example with multiple callbacks vs promises.
The callback is going to be a more nested way in real-time cases.
How Promise deal the same code ? Code Pen
How Promise chain deal the same code ? Code Pen
The Promise object such as then(), catch() returns a separate promise object. Using the object, again make some actions until it’s got the result value.
Hope it will give a clear view of Promises, Please write your questions for any doubts or corrections.
Let’s discuss the next feature of ES6 in the next story.
Next topic: Async/await