{"id":5499,"date":"2020-09-22T08:59:00","date_gmt":"2020-09-22T08:59:00","guid":{"rendered":"https:\/\/azoora.com\/blog\/?p=5499"},"modified":"2020-09-15T09:04:50","modified_gmt":"2020-09-15T09:04:50","slug":"5-awesome-javascript-promise-tricks","status":"publish","type":"post","link":"https:\/\/azoora.com\/blog\/javascript\/5-awesome-javascript-promise-tricks\/","title":{"rendered":"5 Awesome JavaScript Promise Tricks"},"content":{"rendered":"\n<p>The\u00a0<a href=\"https:\/\/javascript.info\/promise-api\"><strong>Promise API<\/strong><\/a>\u00a0changed the game in <strong>JavaScript<\/strong>. We went from abusing\u00a0<code>setTimeout<\/code>s and settling for synchronous operations to doing everything possible to leverage this new async API. Let&#8217;s check out a handful of awesome <strong>Promise API tricks<\/strong>!<\/p>\n\n\n\n<h2>Cancel a fetch Request<\/h2>\n\n\n\n<p>One problem we instantly complained about with promises was not being able to cancel them. A simple&nbsp;<code>promiseInstance.cancel()<\/code>&nbsp;would have been excellent but never came. Instead we were given an API that was way more complicated:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">const controller = new AbortController();\nconst { signal } = controller;\n\nfetch(\"http:\/\/localhost:8000\", { signal }).then(response =&gt; {\n    console.log(`Request 1 is complete!`);\n}).catch(e =&gt; {\n    console.warn(`Fetch 1 error: ${e.message}`);\n});\n\n\/\/ Abort request\ncontroller.abort();<\/pre>\n\n\n\n<p>The magic here is providing the&nbsp;<code>signal<\/code>&nbsp;with each&nbsp;<code>fetch<\/code>&nbsp;request. In the JavaScript world, we inherit difficult APIs and do wonders to abstract them, and thus we&#8217;ll find a way to better abstract this API.<\/p>\n\n\n\n<h2>waitForTime &amp; waitForever<\/h2>\n\n\n\n<p>Waiting for a duration is useful in loads of production and testing situations &#8212; it&#8217;s never ideal but always helpful. I&#8217;ve used two awesome functions to make my life btter:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">\/* Wait for milliseconds *\/\nfunction waitForTime(ms) {\n  return new Promise(r =&gt; setTimeout(r, ms));\n}\n\n\/* Usage *\/\nawait waitForTime(200);\n\n\/* Wait Forever *\/\nfunction waitForever() {\n  return new Promise(r =&gt; {});\n}\n\n\/\/ Usage:\nawait waitForever();<\/pre>\n\n\n\n<p>Don&#8217;t wait for perfect situations, wait for the time you need.<\/p>\n\n\n\n<h2>Async Array Functions<\/h2>\n\n\n\n<p>Array functions like&nbsp;<code>forEach<\/code>,&nbsp;<code>map<\/code>, and other functions are used frequently without the need for them to be synchronous. We don&#8217;t think about it there&#8217;s a fair amount of times we can go async with our operations.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">const promises = [1, 2, 3].map(async (num) =&gt; {\n  console.log(num);\n});\n\nawait promises;<\/pre>\n\n\n\n<p>The difference in caring between async and sync is&nbsp;<code>Promise.allSettled<\/code>. Go async when you can!<\/p>\n\n\n\n<h2>then on Objects<\/h2>\n\n\n\n<p>Did you know that you can arbitrarily add a&nbsp;<code>then<\/code>&nbsp;method on objects to have them treated as a Promise?<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">j = { then: resolve =&gt; fetch(\"\/\").then(resolve) }\n\nj.then(res =&gt; console.log(res));\n\/\/ Response {type: \"basic\", url: \"https:\/\/davidwalsh.name\/\", redirected: false, status: 200, ok: true, \u2026}\n\n\/\/ ... or an await...\nconst response = await j;\n\/\/ Response {type: \"basic\", url: \"https:\/\/davidwalsh.name\/\", redirected: false, status: 200, ok: true, \u2026}<\/pre>\n\n\n\n<p>Now you know! An excellent trick most don&#8217;t know about!<\/p>\n\n\n\n<h2>Detect an Async Function<\/h2>\n\n\n\n<p>Not something you would need to do often but this post is about tricks, right? If you want to detect an asynchronous function, you always can:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">async function myFunction() {\n\n}\n\nconst isAsync = myFunction.constructor.name === \"AsyncFunction\";<\/pre>\n\n\n\n<p>JavaScript Promises are something we every day but a broader look at them allows us to innovate! Have any Promise tricks of your own? Please share!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The\u00a0Promise API\u00a0changed the game in JavaScript. We went from abusing\u00a0setTimeouts and settling for synchronous operations to doing everything possible to leverage this new async API. Let&#8217;s check out a handful of awesome Promise API tricks! Cancel a fetch Request One problem we instantly complained about with promises was not being able to cancel them. A [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":5500,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false},"categories":[77,12],"tags":[73,87],"jetpack_featured_media_url":"https:\/\/azoora.com\/blog\/wp-content\/uploads\/2020\/09\/Promise-JavaScript-Tricks.jpg","jetpack_publicize_connections":[],"jetpack_shortlink":"https:\/\/wp.me\/p7FQPL-1qH","jetpack-related-posts":[],"jetpack_sharing_enabled":true,"jetpack_likes_enabled":true,"_links":{"self":[{"href":"https:\/\/azoora.com\/blog\/wp-json\/wp\/v2\/posts\/5499"}],"collection":[{"href":"https:\/\/azoora.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/azoora.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/azoora.com\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/azoora.com\/blog\/wp-json\/wp\/v2\/comments?post=5499"}],"version-history":[{"count":1,"href":"https:\/\/azoora.com\/blog\/wp-json\/wp\/v2\/posts\/5499\/revisions"}],"predecessor-version":[{"id":5501,"href":"https:\/\/azoora.com\/blog\/wp-json\/wp\/v2\/posts\/5499\/revisions\/5501"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/azoora.com\/blog\/wp-json\/wp\/v2\/media\/5500"}],"wp:attachment":[{"href":"https:\/\/azoora.com\/blog\/wp-json\/wp\/v2\/media?parent=5499"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/azoora.com\/blog\/wp-json\/wp\/v2\/categories?post=5499"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/azoora.com\/blog\/wp-json\/wp\/v2\/tags?post=5499"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}