{"id":214,"date":"2021-09-24T02:44:32","date_gmt":"2021-09-24T02:44:32","guid":{"rendered":"https:\/\/www.bhoomabrsr.com\/blog\/?p=214"},"modified":"2021-09-25T14:07:27","modified_gmt":"2021-09-25T14:07:27","slug":"polyfill-for-async-seriestasks-callback","status":"publish","type":"post","link":"https:\/\/www.bhoomabrsr.com\/blog\/index.php\/2021\/09\/24\/polyfill-for-async-seriestasks-callback\/","title":{"rendered":"Polyfill for Async.series(tasks, callback)"},"content":{"rendered":"\n<p>The series method was quite a different one when we compared it to other sequential call stacks. The series method will take two arguments one is <em>an array of functions<\/em> and another one is the <em>finalCallback<\/em> which is optional to call with the first occurred error and obtained results until then.<\/p>\n\n\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\"> \n\nasync.series( \n  &#x5B;fn-1(callback), fn-2(callback), ... fn-n(callback)], \n  finalCallback( error, results ){ ... }\n);\n<\/pre>\n\n\n\n<p>Now will talk about the implementation. We can solve this problem by making Asyncify each task from the tasks array. This way, we can extract the result from each task, review for errors, and move to the next task. Let&#8217;s move to the code implementation.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><meta charset=\"utf-8\">Asyncify a task<\/h2>\n\n\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\n\nfunction Asyncify(task) {\n  return new Promise((resolve, reject) =&amp;gt; {\n    task((error, result) =&amp;gt; (error ? reject(error) : resolve(result)));\n  });\n}\n\n<\/pre>\n\n\n\n<p>That&#8217;s all we have completed with the implementation, and we need to use this method to queue up the tasks in a sequential way of execution.<\/p>\n\n\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nasync function series(tasks, finalCallback) {\n  const allResults = &#x5B;];\n  for (let i = 0; i &amp;lt; tasks.length; i++) {\n    try {\n      allResults.push(await Asyncify(tasks&#x5B;i]));\n    } catch (error) {\n      finalCallback(error, allResults);\n      break;\n    }\n  }\n  console.log(allResults);\n  finalCallback(null, allResults);\n}\n\n<\/pre>\n\n\n\n<p>This solution is based on Promise API, and you can execute the below code in the browser console for quick analysis. And we can also implement a recursive-based solution and will look into it in our next post. <br>The full spec you can read from <a href=\"https:\/\/caolan.github.io\/async\/v3\/docs.html#series.\">https:\/\/caolan.github.io\/async\/v3\/docs.html#series.<\/a><br><br><\/p>\n\n\n\n<p>Now, add some sample tasks to test and see how this works.<br><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; highlight: [8,14,27]; title: ; notranslate\" title=\"\">\nconst sampleTasks =  &#x5B; function (callback) { setTimeout(function () { console.log(&quot;1&quot;); callback(null, &quot;one&quot;); }, 200); }, function (callback) { setTimeout(function () { console.log(&quot;2&quot;); callback(null, &quot;two&quot;); }, 100); }, function (callback) { setTimeout(function () { console.log(&quot;3&quot;); callback(null, &quot;three&quot;); }, 90); }, function (callback) { setTimeout(function () { console.log(&quot;4&quot;); callback(Error(&quot;some error&quot;)); }, 10); }, function (callback) { setTimeout(function () { console.log(&quot;5&quot;); callback(null, &quot;five&quot;); }, 1000); }, ];\n\nfunction onSeriesCompleted(error, results) {\n  console.log(&quot;Error stack&quot;, error);\n  console.log(&quot;Results of successfully executed tasks&quot;, results);\n}\n\nfunction Asyncify(task) {\n  return new Promise((resolve, reject) =&gt; {\n    task((error, result) =&gt; (error ? reject(error) : resolve(result)));\n  });\n}\n\nasync function series(tasks = &#x5B;], finalCallback) {\n  const allResults = &#x5B;];\n  for (let i = 0; i &lt; tasks.length; i++) {\n    try {\n      allResults.push(await Asyncify(tasks&#x5B;i]));\n    } catch (error) {\n      finalCallback?.(error, allResults);\n      return; \/\/remove if you want continue even after error\n    }\n  }\n  finalCallback?.(null, allResults);\n}\n\nseries(sampleTasks, onSeriesCompleted);\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Output<\/h2>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1168\" height=\"324\" src=\"https:\/\/www.bhoomabrsr.com\/blog\/wp-content\/uploads\/2021\/09\/image-2.png\" alt=\"\" class=\"wp-image-311\"\/><\/figure>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"2048\" height=\"1524\" src=\"https:\/\/www.bhoomabrsr.com\/blog\/wp-content\/uploads\/2021\/09\/code_series.png\" alt=\"\" class=\"wp-image-286\"\/><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>Simple Polyfill for Async.series(tasks, callback)<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[8,14,15,35,33,34],"tags":[],"class_list":["post-214","post","type-post","status-publish","format-standard","hentry","category-async","category-ecma6","category-javascript","category-nodejs","category-specifications","category-standards"],"_links":{"self":[{"href":"https:\/\/www.bhoomabrsr.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/214","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.bhoomabrsr.com\/blog\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.bhoomabrsr.com\/blog\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.bhoomabrsr.com\/blog\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.bhoomabrsr.com\/blog\/index.php\/wp-json\/wp\/v2\/comments?post=214"}],"version-history":[{"count":88,"href":"https:\/\/www.bhoomabrsr.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/214\/revisions"}],"predecessor-version":[{"id":312,"href":"https:\/\/www.bhoomabrsr.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/214\/revisions\/312"}],"wp:attachment":[{"href":"https:\/\/www.bhoomabrsr.com\/blog\/index.php\/wp-json\/wp\/v2\/media?parent=214"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.bhoomabrsr.com\/blog\/index.php\/wp-json\/wp\/v2\/categories?post=214"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.bhoomabrsr.com\/blog\/index.php\/wp-json\/wp\/v2\/tags?post=214"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}