{"id":60799,"date":"2024-03-23T17:56:26","date_gmt":"2024-03-23T12:26:26","guid":{"rendered":"https:\/\/www.tothenew.com\/blog\/?p=60799"},"modified":"2024-03-27T18:02:28","modified_gmt":"2024-03-27T12:32:28","slug":"running-in-parallel-exploring-parallel-promise-execution-with-promise-methods","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/running-in-parallel-exploring-parallel-promise-execution-with-promise-methods\/","title":{"rendered":"Running in Parallel: Exploring Parallel Promise Execution with Promise Methods"},"content":{"rendered":"<p>When we have multiple promises, and we have to execute them parallelly, then we have plenty of promise methods to achieve that based on the requirement. Let&#8217;s explore those methods of Promises::<\/p>\n<div>\n<ol>\n<li><strong>Promise.all()<\/strong><\/li>\n<li><strong>Promise.allSettled()<\/strong><\/li>\n<li><strong>Promise.race()<\/strong><\/li>\n<li><strong>Promise.any()<\/strong><\/li>\n<\/ol>\n<h3>Promise.all()<\/h3>\n<p>The\u00a0<strong><code>Promise.all()<\/code><\/strong> static method takes an iterable(array) of promises as input and returns a single Promise. If all the promises are successfully fulfilled then, it will give a fulfilled promise. If any of the promise rejected, then it will reject and return the error result immediately<\/p>\n<\/div>\n<div>\n<div>\n<pre><code>\/\/ Case 1: All fulfilled\r\nconst promise1 = new Promise((resolve, reject) =&gt; {\r\n    setTimeout(() =&gt; {\r\n        resolve(\"Promise 1 resolved\")\r\n    }, 1000);\r\n});\r\n\r\nconst promise2 = new Promise((resolve, reject) =&gt; {\r\n    setTimeout(() =&gt; {\r\n        resolve(\"Promise 2 resolved\")\r\n    }, 2000);\r\n});\r\n\r\nconst promise3 = new Promise((resolve, reject) =&gt; {\r\n    setTimeout(() =&gt; {\r\n        resolve(\"Promise 3 resolved\")\r\n    }, 3000);\r\n});\r\n\r\nPromise.all([promise1, promise2, promise3]).then((values) =&gt; {\r\n    console.log(values);\r\n});<\/code><\/pre>\n<p>\/\/ output After 3 sec:<\/p>\n<pre>[ 'Promise 1 resolved', 'Promise 2 resolved', 'Promise 3 resolved' ]<\/pre>\n<p><strong>\/\/Case2: Any one of the promise is Rejected<\/strong><br \/>\nIf we take case1 and make the Promise2 rejected, then error result will return immediately<\/p>\n<\/div>\n<\/div>\n<pre><code>const promise2 = new Promise((resolve, reject) =&gt; {\r\n    setTimeout(() =&gt; {\r\n        reject(new Error(\"Promise 2 is rejected\"))\r\n    }, 2000);\r\n});\r\n\r\nPromise.all([promise1, promise2, promise3]).then((values) =&gt; {\r\n    console.log(values);\r\n}).catch((err) =&gt; {\r\n    console.log(err)\r\n});<\/code><\/pre>\n<p>We will get output after 2 sec :\u00a0 Error: Promise 2 is rejectedNote: We can see, in case of Promise rejection, we are getting only the result of the rejected promises, not all the previous promises.<\/p>\n<h3><strong>Promise.allSettled()<\/strong><\/h3>\n<p>It is a static method which takes an iterable (array) of promises as input and returns a single Promise. The returned promise will wait for all promises to settle, even any of them got rejected. The result consist of an array of objects that describe the outcome of each promise. So, we get the state(fulfilled\/rejected) and value of promise in object.<\/p>\n<pre><code>\/\/ Case 1: All fulfilled\r\nconst promise1 = new Promise((resolve, reject) =&gt; {\r\n    setTimeout(() =&gt; {\r\n        resolve(\"Promise 1 resolved\")\r\n    }, 1000);\r\n});\r\n\r\nconst promise2 = new Promise((resolve, reject) =&gt; {\r\n    setTimeout(() =&gt; {\r\n        resolve(\"Promise 2 resolved\")\r\n    }, 2000);\r\n});\r\n\r\nconst promise3 = new Promise((resolve, reject) =&gt; {\r\n    setTimeout(() =&gt; {\r\n        resolve(\"Promise 3 resolved\")\r\n    }, 3000);\r\n});\r\n\r\nPromise.allSettled([promise1, promise2, promise3]).then((values) =&gt; {\r\n    console.log(values);\r\n}).catch((err) =&gt; {\r\n    console.log(err)\r\n});<\/code><\/pre>\n<p>\/\/ Output After 3 sec<\/p>\n<pre>[\r\n{ status: 'fulfilled', value: 'Promise 1 resolved' },\r\n{ status: 'fulfilled', value: 'Promise 2 resolved' },\r\n{ status: 'fulfilled', value: 'Promise 3 resolved' }\r\n]<\/pre>\n<div>\n<div>\n<p><strong>\/\/Case2: Any one of the promises is Rejected<\/strong><br \/>\nIf we take case1 and make the Promise2 rejected, then we will get the result of all the promises irrespective of fulfilled or rejected.<\/p>\n<\/div>\n<\/div>\n<pre><code>const promise2 = new Promise((resolve, reject) =&gt; {\r\n    setTimeout(() =&gt; {\r\n        reject(new Error(\"Promise 2 is rejected\"))\r\n    }, 2000);\r\n});\r\n\r\nPromise.allSettled([promise1, promise2, promise3]).then((values) =&gt; {\r\n    console.log(values);\r\n}).catch((err) =&gt; {\r\n    console.log(err)\r\n});<\/code><\/pre>\n<p>\/\/output after 3 seconds:<\/p>\n<pre>[{\r\n        status: 'fulfilled',\r\n        value: 'Promise 1 resolved'\r\n    },\r\n    {\r\n        status: 'rejected',\r\n        reason: Error: Promise 2 is rejected\r\n        at Timeout._onTimeout......\r\n    },\r\n    {\r\n        status: 'fulfilled',\r\n        value: 'Promise 3 resolved'\r\n    }\r\n]<\/pre>\n<h3><strong>Promise.race():<\/strong><\/h3>\n<p>The\u00a0<strong><code>Promise.race()<\/code><\/strong> static method takes an iterable(array) of promises as input and returns a single Promise.It returns the value of first settled promise, which means, like it&#8217;s a race, whoever settled first, irrespective of fulfilled or rejected, it will return the result<\/p>\n<pre><code>\/\/ Case 1\r\nconst promise1 = new Promise((resolve, reject) =&gt; {\r\n    setTimeout(() =&gt; {\r\n        resolve(\"Promise 1 resolved\")\r\n    }, 1000);\r\n});\r\n\r\nconst promise2 = new Promise((resolve, reject) =&gt; {\r\n    setTimeout(() =&gt; {\r\n        resolve(\"Promise 2 resolved\")\r\n    }, 2000);\r\n});\r\n\r\nconst promise3 = new Promise((resolve, reject) =&gt; {\r\n    setTimeout(() =&gt; {\r\n        resolve(\"Promise 3 resolved\")\r\n    }, 3000);\r\n});\r\n\r\nPromise.race([promise1, promise2, promise3]).then((values) =&gt; {\r\n    console.log(values);\r\n}).catch((err) =&gt; {\r\n    console.log(err)\r\n});<\/code><\/pre>\n<p>As we can see Promise1 only needs 1 sec, so it takes less time than other promises, so it will win the race.<\/p>\n<p>\/\/ Output After 1 second: Promise 1 resolved<\/p>\n<pre><code>\/\/ Case 2 : I have change Timeouts in promise1 and promise2\r\nconst promise1 = new Promise((resolve, reject) =&gt; {\r\n    setTimeout(() =&gt; {\r\n        resolve(\"Promise 1 resolved\")\r\n    }, 2000);\r\n});\r\n\r\nconst promise2 = new Promise((resolve, reject) =&gt; {\r\n    setTimeout(() =&gt; {\r\n        reject(new Error(\"Promise 2 is rejected\"))\r\n    }, 500);\r\n});\r\n\r\nconst promise3 = new Promise((resolve, reject) =&gt; {\r\n    setTimeout(() =&gt; {\r\n        resolve(\"Promise 3 resolved\")\r\n    }, 3000);\r\n});\r\n\r\nPromise.race([promise1, promise2, promise3]).then((values) =&gt; {\r\n    console.log(values);\r\n}).catch((err) =&gt; {\r\n    console.log(err)\r\n});<\/code><\/pre>\n<p>As we can see Promise2 takes only <strong>500ms<\/strong> to settle, so it takes less time than all other promises, so it will win the race<\/p>\n<p>Output After 500 ms: Error: Promise 2 is rejected<\/p>\n<h3>Promise.any():<\/h3>\n<p>It is a static method that takes an iterable(array) of promises as input and returns a single. The returned promise result provide the first fulfilled promise.<\/p>\n<p>Note :Promise.any() looks similar to Promise.race(), but there is a difference, that Promise.any() looks for first fulfilled promise, while promise.race() does not depend on fulfillment, it will return the first settled promise, whether it&#8217;s fulfilled or rejected.<\/p>\n<pre><code>\/\/ Example\r\nconst promise1 = new Promise((resolve, reject) =&gt; {\r\n    setTimeout(() =&gt; {\r\n        resolve(\"Promise 1 resolved\")\r\n    }, 2000);\r\n});\r\n\r\nconst promise2 = new Promise((resolve, reject) =&gt; {\r\n    setTimeout(() =&gt; {\r\n        reject(new Error(\"Promise 2 is rejected\"))\r\n    }, 500);\r\n});\r\n\r\nconst promise3 = new Promise((resolve, reject) =&gt; {\r\n    setTimeout(() =&gt; {\r\n        resolve(\"Promise 3 resolved\")\r\n    }, 3000);\r\n});\r\n\r\nPromise.any([promise1, promise2, promise3]).then((values) =&gt; {\r\n    console.log(values);\r\n}).catch((err) =&gt; {\r\n    console.log(err)\r\n});<\/code><\/pre>\n<p>In this we can see that promise2 is settled within 500ms which is lesser than all promises time, but it is rejected, so, it will not be considered, next lesser time taken(2000 ms) by promise is promise1 and, it is fulfilled also, so, promise1 will be return in result.<\/p>\n<p>\/\/ Output : Promise 1 resolved<\/p>\n<p>Note: Now, you might be thinking what will happen if all the promises got rejected, then we get an AggregateError.<\/p>\n<h2><strong>Conclusion<\/strong><\/h2>\n<p>In this blog, we&#8217;ve explored the Promise API methods that have become essential tools in the toolkit of every JavaScript developer. From <code>Promise.all()<\/code> to <code>Promise.any()<\/code> for managing multiple promises, each method serves a distinct purpose in simplifying asynchronous programming. As you continue your journey in JavaScript development, may the power of promise methods empower you to write cleaner, more resilient code. Happy coding!<\/p>\n<p>Connect with us for more such interesting updates.<\/p>\n<div class=\"ap-custom-wrapper\"><\/div><!--ap-custom-wrapper-->","protected":false},"excerpt":{"rendered":"<p>When we have multiple promises, and we have to execute them parallelly, then we have plenty of promise methods to achieve that based on the requirement. Let&#8217;s explore those methods of Promises:: Promise.all() Promise.allSettled() Promise.race() Promise.any() Promise.all() The\u00a0Promise.all() static method takes an iterable(array) of promises as input and returns a single Promise. If all the [&hellip;]<\/p>\n","protected":false},"author":1714,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":14},"categories":[3429,4684,1185,3038],"tags":[5742,5738,5739,5740,5741],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/60799"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/1714"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=60799"}],"version-history":[{"count":5,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/60799\/revisions"}],"predecessor-version":[{"id":60991,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/60799\/revisions\/60991"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=60799"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=60799"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=60799"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}