{"id":3485,"date":"2022-08-09T18:23:13","date_gmt":"2022-08-09T23:23:13","guid":{"rendered":"https:\/\/www.becomebetterprogrammer.com\/?p=3485"},"modified":"2022-08-09T18:27:18","modified_gmt":"2022-08-09T23:27:18","slug":"javascript-promises","status":"publish","type":"post","link":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-promises\/","title":{"rendered":"The Complete Guide To JavaScript Promises (Explained)"},"content":{"rendered":"\n<p>When working with Async javascript, there are three main methods that you will interact with, namely Callbacks, Async\/Await, and Promises. This post will focus on the latter &#8211; Promises in javascript. Promises are a powerful feature in asynchronous Javascript, and there is a high chance that you will be asked a question regarding Promises in most web developer interviews.<\/p>\n\n\n\n<p><strong>A Promise is an object in asynchronous Javascript representing a &#8220;value&#8221; that is not yet available at the moment. Once the Promise completes successfully, it will return a value that can either be &#8220;Promise-fulfilled&#8221; or &#8220;Promise-rejected.&#8221;<\/strong><\/p>\n\n\n\n<p>This post will give you an in-depth guide on Javascript Promises. It will use simple illustrations that are easy to understand and also show you how to use Promises in your Javascript code.<\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\"><p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<\/div><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-promises\/#Promises_in_Laymans_Terms_%E2%80%93_Breakfast_Example\" >Promises in Layman&#8217;s Terms &#8211; Breakfast Example<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-promises\/#Relation_to_Javascript_Promises\" >Relation to Javascript Promises<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-promises\/#Promise_States\" >Promise States<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-promises\/#Why_Use_Promises_%E2%80%93_Not_Callbacks\" >Why Use Promises &#8211; Not Callbacks?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-promises\/#Promises_to_the_Rescue\" >Promises to the Rescue<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-promises\/#Creating_a_Simple_Promise\" >Creating a Simple Promise<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-promises\/#Promise_Chaining_Nested_Promises\" >Promise Chaining (Nested Promises)<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-promises\/#Advanced_Promise_Methods\" >Advanced Promise Methods<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-promises\/#finally\" >.finally()<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-promises\/#Promiseall_Method\" >Promise.all() Method<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-promises\/#PromiseallSettled_Method\" >Promise.allSettled() Method<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-promises\/#Promiseany_Method\" >Promise.any() Method<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-promises\/#Promiserace_Method\" >Promise.race() Method<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-promises\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Promises_in_Laymans_Terms_%E2%80%93_Breakfast_Example\"><\/span>Promises in Layman&#8217;s Terms &#8211; Breakfast Example<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>You and your friend (Jim) live in the same apartment. One morning, you tell Jim to go to the bakery and get some Doughnuts while you prepare coffee. As Jim leaves, you say to him that if he doesn&#8217;t get Dougnuts, he should send you a text so that you can prepare some Pancakes. If he gets the Dougnuts, he should still text you so you can set up the table.<\/p>\n\n\n\n<p>Jim makes a <strong>PROMISE<\/strong> and says, if he <strong>gets doughnuts<\/strong>, he will send you the message &#8220;<em>Got Them &#8211; set up the table<\/em>.&#8221; If he <strong>doesn&#8217;t get doughnuts<\/strong>, he will send you the text, &#8220;<em>Sorry buddy &#8211; make pancakes<\/em>.&#8221;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Relation_to_Javascript_Promises\"><\/span>Relation to Javascript Promises<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The table below will give you a detailed illustration of how our &#8220;Breakfast scenario&#8221; relates to Promises in Javascript.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Breakfast Scenario<\/strong><\/td><td><strong>Javascript Promises<\/strong><\/td><\/tr><tr><td>1. Your Friend &#8211; Jim<\/td><td>Promise: Jim is the &#8216;Promise&#8217; you are waiting to complete. In this case, the Promise will be &#8216;complete&#8217; when he gets to the bakery.<\/td><\/tr><tr><td>2. Can get doughnuts\/ Might not get doughnuts<\/td><td>Promise Value: (at this moment, it&#8217;s not known since Jim has not reached the bakery)<\/td><\/tr><tr><td>3. Jim got doughnuts<\/td><td>The Promise was fulfilled: It returns the value = &#8220;<em>Got Them &#8211; set up the table.<\/em>&#8220;<\/td><\/tr><tr><td>4. Jim didn&#8217;t get doughnuts<\/td><td>The Promise was rejected: It returns the value = &#8220;<em>Sorry buddy &#8211; make pancakes.<\/em>&#8220;<\/td><\/tr><tr><td>5. Setup the table<\/td><td>Success callback: If Jim got doughnuts, you would set the table.<\/td><\/tr><tr><td>6. Make Pancakes<\/td><td>Failure callback: If Jim didn&#8217;t get doughnuts, you would make pancakes.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Promise_States\"><\/span>Promise States<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Having looked at the illustration above, you will notice that a Promise in Javascript can be in one of three states:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Pending state<\/strong>: Also referred to as the &#8220;initial state.&#8221; Here, the return value is unknown since the Promise is not completed.<\/li><li><strong>Fulfilled state<\/strong>: This state represents a successful operation of the Promise and returns a resolve() value.<\/li><li><strong>Rejected state<\/strong>: This state represents a failed operation of the Promise and returns a reject() value.<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Why_Use_Promises_%E2%80%93_Not_Callbacks\"><\/span>Why Use Promises &#8211; Not Callbacks?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Before introducing Promises in ES6, developers used <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Glossary\/Callback_function\" target=\"_blank\" rel=\"noopener\">Callbacks<\/a> to implement asynchronous Javascript. If you are working on a small application, it would be okay to use callbacks. However, when working with large and complex applications, you might use numerous nested callbacks that eventually lead to <a href=\"http:\/\/callbackhell.com\/\" target=\"_blank\" rel=\"noopener\">callback hell<\/a>.<\/p>\n\n\n\n<p>Below is an example of a callback hell in NodeJS.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>One(function (resultsFromOne) {\n  Two(resultsFromOne, function (resultsFromTwo) {\n    Three(resultsFromTwo, function (resulstsFromThree) {\n      Four(resultsFromThree, function (resultsFromFour) {\n        Five(resultsFromFour, function (resultsFromFive) {\n          Six(resultsFromFive, function (resultsFromSix) {\n            console.log(resultsFromSix);\n          });\n        });\n      });\n    });\n  });\n});<\/code><\/pre>\n\n\n\n<p>That is just a sample code with only simple functions. Imagine if you used these callbacks in a complex NodeJS application where you have to &#8220;read and write&#8221; the filesystem. It would be hectic!<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Promises_to_the_Rescue\"><\/span>Promises to the Rescue<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>You can create Promises in Javascript with the help of the &#8220;new&#8221; keyword. Promises make use of the syntax below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const myPromise = new Promise()<\/code><\/pre>\n\n\n\n<p>Now, the Promise constructor function takes one argument &#8211; a function. To keep things neat and clean, we recommend using an arrow function as shown below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const myPromise = new Promise((resolve, reject)=&gt;{\n    \n})<\/code><\/pre>\n\n\n\n<p>As you can see in the code snippet above, this arrow function takes two arguments &#8211; resolve and reject.<\/p>\n\n\n\n<p class=\"has-luminous-vivid-amber-background-color has-background\"><strong>Tip<\/strong>: You cannot directly mutate the status of a Promise. You instead use the &#8220;Resolve&#8221; and the &#8220;Reject&#8221; functions.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Resolve<\/strong>: When the Resolve function is invoked, it changes the status of the Promise from pending to fulfilled.<\/li><li><strong>Reject<\/strong>: When the Reject function is invoked, it changes the status of the Promise from pending to rejected.<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Creating_a_Simple_Promise\"><\/span>Creating a Simple Promise<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>With the information you have gathered up to this point, you can start writing your first Promise in Javascript. See the code snippet below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const myPromise = new Promise ((resolve,reject)=&gt;{\n    \/\/If Jim got the dougnuts, the Promise is fulfilled\n    \/\/We call the Resolve function\n    resolve(\"Set up the table\")\n    \n    \/\/If Jim didn't get dougnuts, the Promise is rejected\n    \/\/We call the reject function\n    reject(\"Make Pancakes\")\n})<\/code><\/pre>\n\n\n\n<p>From the code snippet above, it&#8217;s clear that the return value of a Promise is determined by some condition. For example, in our breakfast scenario, the condition is &#8220;whether Jim gets the doughnuts or not&#8221;. The code below now includes a condition.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const myPromise = new Promise((resolve, reject) =&gt; {\n  if (\"Jim Got Dougnuts\") {\n    resolve(\"Set up the table\");\n  } \n  \n  else if (\"Jim Didn't get dougnuts\") {\n    reject(\"Make Pancakes\");\n  }\n});<\/code><\/pre>\n\n\n\n<p>Now, you might wonder, &#8220;<em>are Promises simply an if-else statement<\/em>.&#8221; Well, not really. There is a feature that we have not yet talked about.<\/p>\n\n\n\n<p>Javascript Promises give you two methods you can use to execute callback functions depending on the status change of the Promise.<\/p>\n\n\n\n<ul class=\"language-javascript wp-block-list\"><li><code>.then()<\/code>: This method is invoked if the Promise was fulfilled. In other words, the Promise invoked the <code>resolve()<\/code> function.<\/li><li><code>.catch()<\/code>: This method is invoked if the Promise was rejected. In other words, the Promise invoked the <code>reject()<\/code> function.<\/li><\/ul>\n\n\n\n<p class=\"language-javascript\">The code below shows you how to use the <code>.then()<\/code> and <code>.catch()<\/code> methods with Promises.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>myPromise.then((message)=&gt;{\n    console.log(message)\/\/ Here, we log the output of the Resolve() function\n}).catch((error)=&gt;{\n    console.log(error) \/\/ Here, we log the output of the Reject() function\n})<\/code><\/pre>\n\n\n\n<p>Now that you have looked at all the parts of a Promise in Javascript, you can convert the &#8220;breakfast scenario&#8221; to code as shown below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const myPromise = new Promise ((resolve, reject)=&gt;{\n    let JimGotDougnuts = true; \/\/We assume that Jim got the dougnuts\n    if(JimGotDougnuts){\n        resolve(\"Set up the table\")\n    }else{\n        reject(\"Make Pancakes\")\n    }\n})\n\nmyPromise.then((message)=&gt;{\n    console.log(message)\n}).catch((error)=&gt;{\n    console.log(error)\n})\n\n\/\/Output\n\/\/Set up the table<\/code><\/pre>\n\n\n\n<p class=\"language-javascript\">In the above code, since the condition is &#8220;True,&#8221; the Promise invoked the <code>resolve()<\/code> function. In turn, the <code>.then()<\/code> method was invoked and logged the message we got from the Promise.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Promise_Chaining_Nested_Promises\"><\/span>Promise Chaining (Nested Promises)<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Up to this point, using Promises in Javascript might not look that fascinating since we are using a simple example. However, Promises come in handy, especially in solving the issue of callback hells that we looked at above. <\/p>\n\n\n\n<p>Take a look at the code below that makes use of callback functions.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>function FuncOne(callback) {\n  \/\/Pass a condition\n  callback()\n}\n\nfunction funcTwo(callback) {\n  \/\/Pass a condition\n  callback()\n}\n\nfunction funcThree(callback) {\n  \/\/Pass a condition\n  callback()\n}\n\nfuncOne(() =&gt; {\n  funcTwo(() =&gt; {\n    funcThree(() =&gt; {\n      console.log(\"All the functions executed\")\n    })\n  })\n})<\/code><\/pre>\n\n\n\n<p class=\"language-javascript\">In the code snippet above, there are three functions that execute in order. <code>funcOne()<\/code> will execute first, followed by <code>funcTwo()<\/code>, and lastly, <code>funcThree()<\/code> that would log an output if all the conditions were passed. That is quite some mess of using nested callback functions.<\/p>\n\n\n\n<p>So, how would Promises solve such a problem? First, you will need to tweak the way you write your functions. See the code below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>function funcONe(){\n    return new Promise((resolve, reject)=&gt;{\n        \/\/Pass a condition\n        resolve()\n    })\n}\nfunction funcTwo(){\n    return new Promise((resolve, reject)=&gt;{\n        \/\/Pass a condition\n        resolve()\n    })\n}\nfunction funcThree(){\n    return new Promise((resolve, reject)=&gt;{\n        \/\/Pass a condition\n        resolve()\n    })\n}<\/code><\/pre>\n\n\n\n<p>Here, we changed the function to make use of Promises. Now, you can use the syntax below to call the functions.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>funcOne().then(() =&gt; {\n    return funcTwo()\n  }).then(() =&gt; {\n    return funcThree()\n  }).then(() =&gt; {\n    console.log(\"All the functions executed\");\n  });<\/code><\/pre>\n\n\n\n<p class=\"language-javascript\">Here, we are chaining the <code>.then()<\/code> methods of one Promise to the next. A Promise returned from a <code>.then()<\/code> or <code>.catch()<\/code> can be used in the next <code>.then()<\/code> or <code>.catch()<\/code> method in the &#8220;Promise&#8221; chain.<\/p>\n\n\n\n<p>You can go ahead and make the code much cleaner and easy to read, as shown below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>funcOne()\n  .then(funcTwo)\n  .then(funcThree)\n  .then(() =&gt; {\n    console.log(\"We did them all\")\n  })<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Advanced_Promise_Methods\"><\/span>Advanced Promise Methods<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Up to this point, we have looked at the basic usage of Promises in Javascript. However, the Promise object comes with other methods you can use when writing async Javascript.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"finally\"><\/span>.finally()<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"language-javascript\">The <code>.finally()<\/code> method is used similarly to the <code>.then()<\/code> and <code>.catch()<\/code> methods. The main difference is that the code in the <code>.finally()<\/code> method will be executed regardless the Promise fails or rejects.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const myPromise = new Promise ((resolve, reject)=&gt;{\n    let a = true\n    if(a) resolve(\"Test Passed\")\n    reject(\"Test Failed\")\n})\n\nmyPromise.then((message)=&gt;{\n    console.log(message)\n}).catch((error)=&gt;{\n    console.log(error)\n}).finally(()=&gt;{\n    console.log(\"I will always run\")\n})\n\n\/\/Output\n\/\/Test Passed\n\/\/I will always run\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Promiseall_Method\"><\/span>Promise.all() Method<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"language-javascript\">If you have several Promises that you want to execute in parallel, you can use the <code>Promise.all()<\/code> method. <code>Promise.all()<\/code> takes an array of all the Promises you wish to iterate and returns a single value &#8211; an array of the values returned in each Promise. However, this method also follows a set of conditions.<\/p>\n\n\n\n<ul class=\"language-javascript wp-block-list\"><li>The <code>Promise.all()<\/code> will be resolved if all the Promises are resolved.<\/li><li>If the passed arguments in the <code>Promise.all()<\/code> array don&#8217;t return any Promise, it will resolve.<\/li><li>If any of the Promises fails\/ rejects, the <code>Promise.all()<\/code> method will call the <code>catch()<\/code> method on the rejected Promise.<\/li><\/ul>\n\n\n\n<p>See the code below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-js\"><code>const promiseOne = new Promise((resolve, reject)=&gt;{\n    resolve(\"Returned Promise One\")\n})\nconst promiseTwo = new Promise((resolve, reject)=&gt;{\n    resolve(\"Returned Promise Two\")\n})\nconst promiseThree = new Promise((resolve, reject)=&gt;{\n    resolve(\"Returned Promise Three\")\n})\n\nPromise.all(&#91;promiseOne,promiseTwo,promiseThree]).then((message)=&gt;{\n    console.log(message)\n}).catch((error)=&gt;{\n    console.log(error)\n})\n\n\/\/Output\n\/\/  &#91; 'Returned Promise One','Returned Promise Two','Returned Promise Three' ]<\/code><\/pre>\n\n\n\n<p>From the output above, you can see that all the Promises were resolved and returned an array of the values returned in each Promise.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"PromiseallSettled_Method\"><\/span>Promise.allSettled() Method<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"language-javascript\">The <code>Promise.allSettled()<\/code> method is quite similar to the <code>Promise.all()<\/code> method. The only difference is that <code>Promise.allSettled()<\/code> will wait for all Promises to either resolve or reject before invoking the <code>.then()<\/code> method.<\/p>\n\n\n\n<p class=\"language-javascript\">Also the <code>Promise.allSettled()<\/code> only returns an array showing the status of all the Promises (whether a Promise was fulfilled or rejected).<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const promiseOne = new Promise((resolve, reject)=&gt;{\n    resolve(\"Returned Promise One\")\n})\nconst promiseTwo = new Promise((resolve, reject)=&gt;{\n    resolve(\"Returned Promise Two\")\n})\nconst promiseThree = new Promise((resolve, reject)=&gt;{\n    resolve(\"Returned Promise Three\")\n})\n\nPromise.allSettled(&#91;promiseOne,promiseTwo,promiseThree]).then((message)=&gt;{\n    console.log(message)\n})<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"227\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2022\/08\/allSettle-Method-1024x227.png\" alt=\"\" class=\"wp-image-3527\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/08\/allSettle-Method-1024x227.png 1024w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/08\/allSettle-Method-300x66.png 300w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/08\/allSettle-Method-1536x340.png 1536w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/08\/allSettle-Method.png 1942w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption>Promise.allSettled()<\/figcaption><\/figure>\n\n\n\n<p class=\"language-javascript\">If any of Promise returned a <code>reject()<\/code>, you would see the &#8220;rejected&#8221; status in the log. See the code below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const promiseTwo = new Promise((resolve, reject)=&gt;{\n    reject(\"Promise Two Failed\")\n})\n\nPromise.allSettled(&#91;promiseOne,promiseTwo,promiseThree]).then((message)=&gt;{\n    console.log(message)\n})<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"189\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2022\/08\/Promise.all-Rejected-1024x189.png\" alt=\"\" class=\"wp-image-3529\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/08\/Promise.all-Rejected-1024x189.png 1024w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/08\/Promise.all-Rejected-300x55.png 300w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/08\/Promise.all-Rejected-1536x283.png 1536w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/08\/Promise.all-Rejected.png 1976w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Promiseany_Method\"><\/span>Promise.any() Method<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"language-javascript\">This method is similar to the <code>Promise.all()<\/code> method as it also takes an array of Promises. However, unlike <code>Promise.all()<\/code> which will wait for all the Promises to resolve, the <code>Promise.any()<\/code> method only waits for one Promise to resolve before calling the <code>.then()<\/code> function on that Promise.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const promiseOne = new Promise((resolve, reject)=&gt;{\n    reject(\"Returned Promise One\")\n})\nconst promiseTwo = new Promise((resolve, reject)=&gt;{\n    resolve(\"Returned Promise Two\")\n})\n\nPromise.any(&#91;promiseOne,promiseTwo,promiseThree]).then((message)=&gt;{\n    console.log(message)\n})\n\/\/Output\n\/\/Returned Promise Two<\/code><\/pre>\n\n\n\n<p class=\"language-javascript\">In the code above, we have two Promises &#8211; (promiseOne and promiseTwo). <em>promiseOne<\/em> returns a <code>reject()<\/code> while <em>promiseTwo<\/em> returns a resolve(). Since the <code>Promise.any()<\/code> method only waits for one &#8220;Promise&#8221; to resolve, it will call the <code>.then()<\/code> method on <em>promiseTwo<\/em>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Promiserace_Method\"><\/span>Promise.race() Method<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"language-javascript\">The <code>Promise.race()<\/code> is similar to the <code>Promise.any()<\/code> method. The only difference is that <code>Promise.race()<\/code> will wait for the first Promise to either resolve or reject before calling the <code>.then()<\/code> or <code>.catch()<\/code> method on that Promise.<\/p>\n\n\n\n<p class=\"language-javascript has-vivid-green-cyan-background-color has-background\"><strong>Tip<\/strong>: <code>Promise.any()<\/code> only waits for the Promise that will be the first to resolve\/ succeed. <code>Promise.race()<\/code> only wait for the Promise that will be the first to resolve or reject.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const promiseOne = new Promise((resolve, reject)=&gt;{\n    reject(\"Returned Promise One\")\n})\nconst promiseTwo = new Promise((resolve, reject)=&gt;{\n    resolve(\"Returned Promise Two\")\n})\n\nPromise.race(&#91;promiseOne,promiseTwo]).then((message)=&gt;{\n    console.log(message)\n}).catch((error)=&gt;{console.log(error)})\n\n\/\/Output\n\/\/Returned Promise One<\/code><\/pre>\n\n\n\n<p>In the output above, we see that we returned <em>promiseOne<\/em>. That&#8217;s because it was the first Promise to return a value.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>This post has given you a comprehensive guide on Javascript Promises. Below are key points you can always refer to when working with Promises.<\/p>\n\n\n\n<ul class=\"language-javascript wp-block-list\"><li><code>Promise.all()<\/code>: This method waits for all the Promises passed as an array to resolve and returns a single array of values returned in all Promises.<\/li><li><code>Promise.allSettled()<\/code>: This method takes an array of Promises and waits for all the Promises to either resolve or reject. It will then return an array showing the status of each Promise (fulfilled or rejected) and the value returned in each Promise.<\/li><li><code>Promise.any()<\/code>: This method takes an array of Promises and then waits for the first Promise to resolve before calling the <code>.then()<\/code> method on that Promise.<\/li><li><code>Promise.race()<\/code>: This method takes an array of Promises and waits for the first Promise to either resolve or reject before calling the <code>.then()<\/code> or <code>.catch()<\/code> method on that Promise.<\/li><\/ul>\n\n\n\n<p><strong>Was this article helpful?<\/strong><\/p>\n\n\n\n<p>Share it with other developers who want an in-depth explanation of Promises in Javascript. You can also share your thoughts by replying on Twitter of\u00a0<a href=\"https:\/\/twitter.com\/bbprogrammer\/status\/1459150572565798916\" target=\"_blank\" rel=\"noreferrer noopener\">Become A Better Programmer<\/a>\u00a0or to\u00a0<a href=\"https:\/\/twitter.com\/NetmattaTech\" target=\"_blank\" rel=\"noreferrer noopener\">my personal account<\/a>.<\/p>\n\n\n\n<figure class=\"wp-block-embed aligncenter is-type-rich is-provider-twitter wp-block-embed-twitter\"><div class=\"wp-block-embed__wrapper\">\nhttps:\/\/twitter.com\/bbprogrammer\/status\/1557146411032104960\n<\/div><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>When working with Async javascript, there are three main methods that you will interact with, namely Callbacks, Async\/Await, and Promises. This post will focus on the latter &#8211; Promises in javascript. Promises are a powerful feature in asynchronous Javascript, and there is a high chance that you will be asked a question regarding Promises in &#8230; <a title=\"The Complete Guide To JavaScript Promises (Explained)\" class=\"read-more\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-promises\/\" aria-label=\"More on The Complete Guide To JavaScript Promises (Explained)\">Read more<\/a><\/p>\n","protected":false},"author":5,"featured_media":3574,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"nf_dc_page":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[16],"tags":[],"class_list":["post-3485","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-javascript","generate-columns","tablet-grid-50","mobile-grid-100","grid-parent","grid-50"],"_links":{"self":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/3485","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/comments?post=3485"}],"version-history":[{"count":5,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/3485\/revisions"}],"predecessor-version":[{"id":3576,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/3485\/revisions\/3576"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media\/3574"}],"wp:attachment":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media?parent=3485"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/categories?post=3485"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/tags?post=3485"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}