Handling Multiple Asynchronous Operations Using Promise

What are JavaScript Promises?

 
We all have used asynchronous callbacks in our applications. We would need to wait for the result of an asynchronous operation to proceed. Earlier we have used callbacks for achieving this, but faced a lot of difficulties. Promise helps us in making this Asynchronous operation Synchronous.
 
Promise can be considered as a placeholder or container for storing the result from an asynchronous operation.
 
A promise can be in any of the below states,
  • Pending - This will be the initial state and the asynchronous operation is in process.
  • Resolved or fulfilled - The operation is completed successfully and returns the results as a Promise object.
  • Rejected - Operation is failed.
Example
  1. var message1 = function(msg) {  
  2.     return new Promise((resolve, reject) => {  
  3.         if (msg) {  
  4.             resolve(msg);  
  5.         } else {  
  6.             reject(Error("Invalid string"));  
  7.         }  
  8.     });  
  9. };  
  10. var message2 = function(msg) {  
  11.     return new Promise((resolve, reject) => {  
  12.         if (msg) {  
  13.             resolve(msg);  
  14.         } else {  
  15.             reject(Error("Invalid string"));  
  16.         }  
  17.     });  
  18. };  
  19. var message3 = = function(msg) {  
  20.     return new Promise((resolve, reject) => {  
  21.         if (msg) {  
  22.             resolve(msg);  
  23.         } else {  
  24.             reject(Error("Invalid string"));  
  25.         }  
  26.     });  
  27. };  
  28. message1("First Promise Resolved").then((result) => {  
  29.     console.log(result);  
  30.     return message2("Second Promise Resolved");  
  31. }).then((result) => {  
  32.     console.log(result);  
  33.     return message3("Third Promise Resolved");  
  34. }).then((result) => {  
  35.     console.log(result);  
  36. }).catch((err) => {  
  37.     console.log(err);  
  38. });  
We can chain multiple asynchronous operations using then call back as above. But the real problem came into the picture when we need to use asynchronous calls inside a loop. In that case, we can use the static method Promise. all().
 

Promise.all() static method

 
This method accepts a list of promises and returns a single promise. This single promise will get resolved only when all input promises are resolved and will be in a rejected state if any of the input promises is rejected.
 
Example
  1. let tmpArray = [1, 2, 3, 4];  
  2. let promiseArray = [];  
  3. private getData(id) {  
  4.     return new Promise((resolve, reject) => {  
  5.         fetch("testapi/" + id).then(r =>  
  6.             return r.json()).then((data) => {  
  7.             resolve(data.value);  
  8.         });  
  9.     });  
  10. }  
  11. private resolvePromises() {  
  12.     tmpArray.forEach(  
  13.         (id) => {  
  14.             promiseArray.push(getData(id));  
  15.         });  
  16.     Promise.all(promiseArray).then((results) => {  
  17.         results.forEach(  
  18.             (result) => {  
  19.                 console.log(result);  
  20.             });  
  21.     });  
  22. }