{"id":1486,"date":"2021-12-11T16:43:06","date_gmt":"2021-12-11T15:43:06","guid":{"rendered":"https:\/\/nguenkam.com\/blog\/?p=1486"},"modified":"2021-12-11T16:44:59","modified_gmt":"2021-12-11T15:44:59","slug":"asynchronous-programming-with-async-and-await","status":"publish","type":"post","link":"https:\/\/nguenkam.com\/blog\/index.php\/2021\/12\/11\/asynchronous-programming-with-async-and-await\/","title":{"rendered":"Asynchronous programming with async and await"},"content":{"rendered":"\n<p><\/p>\n\n\n\n<h4>The <strong><span class=\"has-inline-color has-vivid-cyan-blue-color\">async<\/span><\/strong> keyword<\/h4>\n\n\n\n<p>First, we have the async keyword, which you put in front of a function declaration to turn it into an asynchronous function. <\/p>\n\n\n\n<p><em>An asynchronous function is a function that will react to a possible use of the await keyword to invoke asynchronous code.<\/em><\/p>\n\n\n\n<p>Let us turn one function into an asynchronous function : <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>async function hello() { return \"Bonjour\" };\nhello();\n\n\/\/or\nlet hello = async function() { return \"Bonjour\" };\nhello();\n\n\/\/or\nlet hello = async () =&gt; { return \"Bonjour\" };\nhello();<\/code><\/pre>\n\n\n\n<p>Invoking the function now returns a promise. This is one of the characteristics of asynchronous functions &#8211; <span class=\"has-inline-color has-vivid-red-color\">their return values ??are necessarily converted to promises.<\/span><\/p>\n\n\n\n<p>To actually consume the returned value when the promise is fulfilled, since it returns a promise, we could use a <span class=\"has-inline-color has-vivid-cyan-blue-color\"><strong>.then ()<\/strong><\/span> block:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>hello().then((value) =&gt; console.log(value));<\/code><\/pre>\n\n\n\n<p><em>Thus, the <span class=\"has-inline-color has-vivid-cyan-blue-color\"><strong>async <\/strong><\/span>keyword is added to functions to tell them to return a <span class=\"has-inline-color has-vivid-cyan-blue-color\"><strong>promise<\/strong><\/span> rather than directly returning the value<\/em>.<\/p>\n\n\n\n<div style=\"height:100px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<h4>The <span class=\"has-inline-color has-vivid-cyan-blue-color\">await<\/span> keyword<\/h4>\n\n\n\n<p>The advantage of an <span class=\"has-inline-color has-vivid-cyan-blue-color\"><strong>asynchronous function<\/strong><\/span> only becomes apparent when you combine it with the <span class=\"has-inline-color has-vivid-cyan-blue-color\"><strong>await<\/strong><\/span> keyword. await only works inside asynchronous functions in regular JavaScript code, but it can be used on its own with JavaScript modules.<\/p>\n\n\n\n<p><em>await can be placed in front of any asynchronous function based on a promise to pause your code on that line until the promise is fulfilled, then return the resulting value.<\/em><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>async function hello() {\n  return salutation = await Promise.resolve(\"Bonjour\");\n};\n\nhello().then(console.log);<\/code><\/pre>\n\n\n\n<p><em>The example above is not very useful, although it serves to illustrate the syntax.<\/em><\/p>\n\n\n\n<p>Following, ein better explained example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>async function myFetch() {\n  let response = await fetch('coffee.jpg');\n  if (!response.ok) {\n    throw new Error(`Erreur HTTP ! statut : ${response.status}`);\n  }\n  return await response.blob();\n\n}\n\nmyFetch().then((blob) =&gt; {\n  let objectURL = URL.createObjectURL(blob);\n  let image = document.createElement('img');\n  image.src = objectURL;\n  document.body.appendChild(image);\n}).catch(e =&gt; console.log(e));<\/code><\/pre>\n\n\n\n<h4>But how does it work?<\/h4>\n\n\n\n<p>the .catch () block will catch errors occurring both in the asynchronous function call and in the chain of promises.<\/p>\n\n\n\n<p>Let\u00b4s notice that we&#8217;ve wrapped the code inside a function, and we&#8217;ve included the <strong>async keyword <\/strong>before the <strong>function keyword<\/strong>. This is necessary &#8211; we need to create an async function to define a block of code in which we will run our async code; <em><span class=\"has-inline-color has-vivid-cyan-blue-color\"><strong>as we said before, await only works inside async functions.<\/strong><\/span><\/em><\/p>\n\n\n\n<p>Inside the definition of the <strong>myFetch ()<\/strong> function, instead of having to chain a .then () block at the end of each promise-based method, we just add an <strong>await <\/strong>keyword before the method call, then assign the result to a variable. <\/p>\n\n\n\n<p>The await keyword causes the JavaScript runtime to pause our code on this line, not allowing other code to execute in the meantime until the asynchronous function call returned its result &#8211; <span class=\"has-inline-color has-vivid-cyan-blue-color\"><em><strong>very useful if the following code depends on this result!<\/strong><\/em><\/span><\/p>\n\n\n\n<p>Once that&#8217;s done, our code continues to run from the next line. For example :<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>let response = await fetch('coffee.jpg');<\/code><\/pre>\n\n\n\n<p>The response returned by the filled <strong>fetch ()<\/strong> promise is assigned to the response variable when that response becomes available, and the parser pauses on that line until that happens. Once the answer is available, the parser moves to the next line, which creates a blob from it. This line also invokes a promise-based async method, so we&#8217;re using await here as well. When the result of the operation comes back, we return it out of the myFetch () function.<\/p>\n\n\n\n<p>This means that when we call the<strong> myFetch ()<\/strong> function, it returns a promise, so that we can chain a .<strong>then ()<\/strong> at the end of it inside which we manage the display of the blob to the screen.<\/p>\n\n\n\n<div style=\"height:100px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<h5>Reference:<\/h5>\n\n\n\n<p><a href=\"https:\/\/developer.mozilla.org\/\">https:\/\/developer.mozilla.org\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The async keyword First, we have the async keyword, which you put in front of a function declaration to turn it into an asynchronous function. An asynchronous function is a function that will react to a possible use of the await keyword to invoke asynchronous code. Let us turn one function into an asynchronous function [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":1487,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[5],"tags":[417,418,85],"_links":{"self":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/1486"}],"collection":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/comments?post=1486"}],"version-history":[{"count":2,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/1486\/revisions"}],"predecessor-version":[{"id":1489,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/1486\/revisions\/1489"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/media\/1487"}],"wp:attachment":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/media?parent=1486"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/categories?post=1486"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/tags?post=1486"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}