<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kunal Mukherjee on Medium]]></title>
        <description><![CDATA[Stories by Kunal Mukherjee on Medium]]></description>
        <link>https://medium.com/@kunalm.3701?source=rss-aa107f8be088------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rNvZGbXy2gjvkGR6v9qQrA.jpeg</url>
            <title>Stories by Kunal Mukherjee on Medium</title>
            <link>https://medium.com/@kunalm.3701?source=rss-aa107f8be088------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 05:17:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kunalm.3701/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Resolving promises concurrently in JavaScript— The foolproof way]]></title>
            <link>https://medium.com/@kunalm.3701/resolving-promises-concurrently-in-javascript-the-foolproof-way-5278a3d4aad0?source=rss-aa107f8be088------2</link>
            <guid isPermaLink="false">https://medium.com/p/5278a3d4aad0</guid>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Kunal Mukherjee]]></dc:creator>
            <pubDate>Fri, 02 Oct 2020 18:13:48 GMT</pubDate>
            <atom:updated>2020-10-02T18:13:48.187Z</atom:updated>
            <content:encoded><![CDATA[<p>I am quite sure most of us have experienced a situation wherein we need to run certain slow running asynchronous tasks in parallel like sending bulk emails to users, making HTTP calls that are independent of each other, saving records to the database, etc.</p><p>In such situations, we ended up using either <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all">Promise.all</a>(available both in browser and Node.JS) or some third party solutions like the <a href="https://www.npmjs.com/package/async">async</a>library’s <a href="https://caolan.github.io/async/v3/docs.html#parallel">async.parallel</a>which by the way uses callbacks.</p><p>But we all know the fail-fast behavior of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all">Promise.all</a>, quoting MDN:</p><blockquote>The <strong>Promise.all()</strong> method takes an iterable of promises as an input, and returns a single <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a> that resolves to an array of the results of the input promises. This returned promise will resolve when all of the input&#39;s promises have resolved, or if the input iterable contains no promises. <strong>It rejects immediately upon any of the input promises rejecting or non-promises throwing an error, and will reject with this first rejection message / error.</strong></blockquote><p>So, the other day I was wondering how can we work-around this fail-fast limitation and get to a solution which like works seamlessly in both browser and Node.JS.</p><p>I began reading lots of articles and blogs and stumbled upon the Bluebirdlibrary’s <a href="http://bluebirdjs.com/docs/api/reflect.html">reflect</a>, though using this method would mean installing Bluebird library which would eventually add up more bloat to the project, thanks to NodeJS dependency hell.</p><p>The function whenAllreturns a promise when all promises are settled (i.e either resolvedor rejected)</p><pre>/**<br> * Returns a promise when all the promises settles<br> * <a href="http://twitter.com/param">@param</a> {Promise[]} promises - Promises to resolve<br> * <a href="http://twitter.com/return">@return</a> {Object[]} Array of resolved/rejected values with their respective statuses<br>*/<br>const whenAll = (promises) =&gt; {<br> const reflect = (promise) =&gt; {<br>  return promise.then((resolvedValue) =&gt; ({<br>   status: &#39;Resolved&#39;,<br>   data: resolvedValue<br>  }))<br>  .catch((rejectedErr) =&gt; ({<br>   status: &#39;Rejected&#39;,<br>   error: rejectedErr<br>  }));<br> };<br> <br> return Promise.all(promises.map(reflect));<br>};</pre><p>It essentially relies on the fact that Promise.all expects an iterable array, so we basically transform each array element which is a promise using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">Array.prototype.map</a> in a closure function called reflectand return an object with a status flag indicating the result of the promise.</p><p>So I quickly wrote some code utilizing the above function to make 5 HTTP requests without failing fast.</p><pre>&#39;use strict&#39;;</pre><pre>const promisifyXHR = (url) =&gt; {<br> return new Promise((resolve, reject) =&gt; {<br>  const xhr = new XMLHttpRequest();<br>  xhr.open(&#39;GET&#39;, url);<br>  <br>  xhr.onload = function () {<br>    if (this.status &gt;= 200 &amp;&amp; this.status &lt; 300) {<br>        return resolve(xhr.response);<br>    } else {<br>       return reject({<br>        status: this.status,<br>        statusText: xhr.statusText<br>       });<br>    }<br>  };<br>  <br>  xhr.onerror = function () {<br>    return reject({<br>      status: this.status,<br>      statusText: xhr.statusText<br>    });<br>  };<br>  <br>  xhr.send();<br> });<br>};</pre><pre>const whenAll = (promises) =&gt; {<br> const reflect = (promise) =&gt; {<br>  return promise.then((resolvedValue) =&gt; ({<br>      status: &#39;Resolved&#39;,<br>      data: resolvedValue<br>  }))<br>  .catch((rejectedErr) =&gt; ({<br>      status: &#39;Rejected&#39;,<br>      error: rejectedErr<br>  }));<br> };<br> <br> return Promise.all(promises.map(reflect));<br>};</pre><pre>const filterPromiseResult = (settledPromises, type) =&gt; settledPromises.filter((settledPromises) =&gt; settledPromise.status === type);</pre><pre>(async () =&gt; {<br> try {<br>      const fetchPromises = [<br>         &#39;<a href="https://jsonplaceholder.typicode.com/todos/1&#39;">https://jsonplaceholder.typicode.com/todos/1&#39;</a>,<br>         &#39;<a href="https://jsonplaceholder.typicode.com/todos/2&#39;">https://jsonplaceholder.typicode.com/todos/2&#39;</a>,<br>         &#39;<a href="https://invalid-route&/#39;">https://invalid-route&#39;</a>,<br>         &#39;<a href="https://jsonplaceholder.typicode.com/todos/3&#39;">https://jsonplaceholder.typicode.com/todos/3&#39;</a>,<br>         &#39;<a href="https://jsonplaceholder.typicode.com/todos/5&#39;">https://jsonplaceholder.typicode.com/todos/5&#39;</a><br>      ].map(promisifyXHR);<br>  <br>     const settledPromises = await whenAll(fetchPromises);<br>  <br>    /* We can also filter promises <br>       based on their statuses<br>    */</pre><pre>   const resolvedPromises = filterPromiseResult(settledPromises, &#39;Resolved&#39;);<br>   const rejectedPromises = filterPromiseResult(settledPromises, &#39;Rejected&#39;);</pre><pre>  console.table(resolvedPromises);<br>  console.table(rejectedPromises);</pre><pre> } catch (err) {<br>  console.error(err);<br> }<br>})();</pre><p>Which then gives us -</p><figure><img alt="whenAll result" src="https://cdn-images-1.medium.com/max/1024/1*CdhOUGEmGXsgarrS8j9Whg.png" /></figure><p>In 2020 there’s a new method <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled">Promise.allSettled</a> which essentially does the same thing where whenAllseems like re-inventing the wheel, but the support is still in early stages and only available in the latest of browsers and the latest stable release of Node.JS until then whenAll seems a viable workaround for the above situations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5278a3d4aad0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>