<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Sébastien Stormacq</title>
    <description>The latest articles on DEV Community by Sébastien Stormacq (@sebsto).</description>
    <link>https://dev.to/sebsto</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F183925%2F85b4b224-9fc3-423b-a25d-62215204abf2.png</url>
      <title>DEV Community: Sébastien Stormacq</title>
      <link>https://dev.to/sebsto</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/sebsto"/>
    <language>en</language>
    <item>
      <title>Master asynchronous API calls in Javascript</title>
      <dc:creator>Sébastien Stormacq</dc:creator>
      <pubDate>Tue, 25 Jun 2019 09:35:30 +0000</pubDate>
      <link>https://dev.to/sebsto/master-asynchronous-api-calls-in-javascript-j51</link>
      <guid>https://dev.to/sebsto/master-asynchronous-api-calls-in-javascript-j51</guid>
      <description>&lt;p&gt;I am often replying to Javascript &lt;a href="https://stackoverflow.com/questions/55060415/connect-aws-mobile-backend-to-dynamodb?noredirect=1#comment96870590_55060415" rel="noopener noreferrer"&gt;programming questions&lt;/a&gt;about issues related to a lack of understanding of the asynchronous nature of most Javascript API and the proper way to write asynchronous code.  Some documentation or examples found through search engines are outdated and not reflecting 2019's language features and best practices.&lt;/p&gt;

&lt;p&gt;There are numerous good blog posts, &lt;a href="https://medium.com/@tkssharma/writing-neat-asynchronous-node-js-code-with-promises-async-await-fa8d8b0bcd7c" rel="noopener noreferrer"&gt;like this one&lt;/a&gt;, to explain the concepts of asynchronous coding and even more to describe correct usage of the &lt;a href="https://www.promisejs.org/patterns/" rel="noopener noreferrer"&gt;Promise pattern&lt;/a&gt;, I don't want to write a "me too" article, but rather just focus one three code sample : the good, the bad and the ugly.  Or should I say : the modern, the old and the antique ?&lt;/p&gt;

&lt;p&gt;So, using three simple code samples, let's see how you can refactor your code from a callback approach (the ugly), to a Promise approach with &lt;code&gt;.then()&lt;/code&gt; constructs (the bad) to a modern Promise approach using &lt;code&gt;async&lt;/code&gt;/&lt;code&gt;await&lt;/code&gt; keywords (the correct way of writing modern code).&lt;/p&gt;

&lt;p&gt;The oldest and traditional approach was to pass callback function to your asynchronous function.  Upon termination, the asynchronous function would simply call your callback function.  Please do not do that anymore.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F00wfsbpaku2v79ju9y96.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F00wfsbpaku2v79ju9y96.png" width="545" height="605"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nv"&gt;$ &lt;/span&gt;node async_demo_1.js
Started
Ended
callback &lt;span class="o"&gt;!&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;(&lt;a href="https://gist.github.com/sebsto/14d230185dbead90adb6a29fc2f410e9" rel="noopener noreferrer"&gt;code&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;Notice &lt;code&gt;callback&lt;/code&gt; is called after &lt;code&gt;Ended&lt;/code&gt; because program execution continues while &lt;code&gt;asyncWorker()&lt;/code&gt; is executed.&lt;/p&gt;

&lt;p&gt;To avoid having to manage callbacks hell, many programing languages are now proposing the concept of Promises.  Converting old callback-based code to Promises is easy :&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;immediately return a &lt;code&gt;new Promise()&lt;/code&gt; object.&lt;/li&gt;
&lt;li&gt;the Promise constructor takes one function argument : &lt;code&gt;(resolve, reject) =&amp;gt; { ... }&lt;/code&gt; &lt;/li&gt;
&lt;li&gt;whenever a result is available call &lt;code&gt;resolve(return_value)&lt;/code&gt; or call &lt;code&gt;reject(reason)&lt;/code&gt; in case of an error&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fv4p55j44hb2r89ak2krq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fv4p55j44hb2r89ak2krq.png" width="646" height="649"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nv"&gt;$ &lt;/span&gt;node async_demo_2.js
Started
Ended
callback &lt;span class="o"&gt;!&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;(&lt;a href="https://gist.github.com/sebsto/028d23a01c93b7d15aa349c81feba819" rel="noopener noreferrer"&gt;code&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;Notice &lt;code&gt;callback&lt;/code&gt; is still called after &lt;code&gt;Ended&lt;/code&gt;.  Also notice the asynchronous function immediately returns a &lt;code&gt;Promise&lt;/code&gt; object.  &lt;/p&gt;

&lt;p&gt;This simplifies a lot writing asynchronous code, but you still end up with &lt;code&gt;.then().catch()&lt;/code&gt; nightmare. So, to remove these &lt;code&gt;.then().catch()&lt;/code&gt; the last transformation step is to migrate your code to &lt;code&gt;await&lt;/code&gt; / &lt;code&gt;async&lt;/code&gt; keywords, as shown below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw3rn3ynbzqu6ta6s4s6d.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw3rn3ynbzqu6ta6s4s6d.png" width="646" height="559"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nv"&gt;$ &lt;/span&gt;node async_demo_3.js
Started
callback &lt;span class="o"&gt;!&lt;/span&gt;
Ended
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;(&lt;a href="https://gist.github.com/sebsto/382b0d41ee933ea5f512d1c2e1be2707" rel="noopener noreferrer"&gt;code&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;Notice the output is now in the logical order.  &lt;code&gt;await&lt;/code&gt; blocks the execution until that function finishes.  Also notice that the only change made to the asynchronous function is the addition of the &lt;code&gt;async&lt;/code&gt; keyword at the start of it.&lt;/p&gt;

&lt;p&gt;Let's finish by looking at how you can wrap AWS Services calls made with the &lt;a href="https://aws.amazon.com/sdk-for-node-js/" rel="noopener noreferrer"&gt;AWS SDK for Javascript&lt;/a&gt;{:target="_blank"} with &lt;code&gt;async&lt;/code&gt; and &lt;code&gt;await&lt;/code&gt;.  Here is a &lt;a href="https://aws.amazon.com/dynamodb/getting-started/" rel="noopener noreferrer"&gt;DynamoDB&lt;/a&gt; &lt;a href="https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#update-property" rel="noopener noreferrer"&gt;&lt;code&gt;update&lt;/code&gt;&lt;/a&gt; example.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fevkqf3o6l1mu4dy8ss9n.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fevkqf3o6l1mu4dy8ss9n.png" width="800" height="795"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;(&lt;a href="https://gist.github.com/sebsto/96595219569f2335891d00415e2d1569" rel="noopener noreferrer"&gt;code&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;The idea is the same : the function immediately returns a &lt;code&gt;Promise&lt;/code&gt;.  Then your function calls the AWS SDK, using a callback.  The successful callback eventually calls &lt;code&gt;resolve(&amp;lt;any data&amp;gt;)&lt;/code&gt; to pass the result back to the caller.  In case of error, the error handling code calls &lt;code&gt;reject()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;To wrap up, going from callback to &lt;code&gt;async&lt;/code&gt; / &lt;code&gt;await&lt;/code&gt; is pretty straigthforward once you know how to do it.  Now that you read this short post, there is no reason to not do it :-). All &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#Browser_compatibility" rel="noopener noreferrer"&gt;browser's recent versions&lt;/a&gt; do include support for these constructs, so does NodeJS since version 7.6.0.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>asynchronous</category>
      <category>promises</category>
      <category>aws</category>
    </item>
  </channel>
</rss>
