
Promise object helps you to run the functions asynchronously (sequentially) and use their return values when the processing is done.
Promises accept an executor function with the arguments resolve and reject methods. Once the task inside the Promise is completed, Promise can either be resolved or rejected.
States of Promise
A Promise passes through the states given below.
- pending initial state of Promise when the instance gets created.
- fulfilled the operation completed successfully.
- rejected the operation failed.
Generally, Promises are created using a new keyword. Thus, when the instance gets created, then the stage is known as the pending stage and the task (or code) inside Promise block executes in this stage. On completion of the code execution, either Promise gets resolved or rejected.
then and catch
The callback methods, then and catch, are triggered when a Promise gets resolved or rejected respectively. When Promise gets resolved, Promise can send a value to the .then function. When Promise gets rejected, it can send an error message to the .catch function. In .then or .catch function, another Promise can be queued up.
Example
- var promise = new Promise(function(resolve, reject) {
- setTimeout(function() {
- resolve(“promise resolved”);
- }, 2000)
- });
- promise.then(function(msg) {
- console.log("then: " + msg); //then: promise resolved
- }).catch(function(val) {
- console.log("catch: " + val)
- });
Promise.all
It accepts an array of Promises as a parameter. Promise.all gets fulfilled when all Promises in the array are resolved or gets rejected when any Promise gets rejected. If all Promises are resolved, .then callback method gets triggered with an array of the values in the same order of Promises added in the array parameter. If any Promise gets rejected, .catch method gets triggered with the error message returned by the rejected Promise.
Example

Join the conversation! Your thoughts help the community grow.