{"id":313,"date":"2019-02-28T01:46:32","date_gmt":"2019-02-27T20:16:32","guid":{"rendered":"http:\/\/uitutorials.in\/wp\/?p=313"},"modified":"2020-10-06T13:32:53","modified_gmt":"2020-10-06T08:02:53","slug":"javascript-async-await","status":"publish","type":"post","link":"https:\/\/uitutorials.in\/wp\/javascript-async-await\/","title":{"rendered":"Javascript : Async\/Await"},"content":{"rendered":"<h2>Async\/Await<\/h2>\n<p>Inside a function marked as <strong>async<\/strong>, you are allowed to place the <strong>await<\/strong> keyword in front of an expression that returns a <strong>Promise<\/strong>. When you do, the execution is paused until the <strong>Promise<\/strong> is resolved.<\/p>\n<p>Before we dive into it, let\u2019s take a moment to familiarize you with the <strong>async\/await<\/strong> style. First, <strong>async\/await<\/strong> makes the asynchronous code appear and behave like synchronous code. Being that it was built on top of <strong>Promises<\/strong>, you could simply see it as a new way of writing synchronous code. Just like <strong>Promises<\/strong> themselves, <strong>async\/await<\/strong> is equally non-blocking.<\/p>\n<p>The purpose of <strong>async\/await<\/strong> functions is to simplify the behavior of using <strong>Promises<\/strong> synchronously and to perform some behavior on a group of <strong>Promises<\/strong>. Just as <strong>Promises<\/strong> are similar to structured callbacks, one can say that <strong>async\/await<\/strong> is similar to combining <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Guide\/Iterators_and_Generators\">generators<\/a> and <strong>Promises<\/strong>.<br \/>\nBasically, there are two keywords involved, <strong>async<\/strong> and <strong>await<\/strong>, let\u2019s understand them better:<\/p>\n<h3>Async<\/h3>\n<p>Putting the keyword <strong>async<\/strong> before a function tells the function to return a <strong>Promise<\/strong>. If the code returns something that is not a <strong>Promise<\/strong>, then JavaScript automatically wraps it into a resolved promise with that value e.g when it returns an <strong>AsyncFunction<\/strong> object:<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">async function oddNumber() {\r\n      return 7;\r\n    }\r\n<\/code><\/pre>\n<p>Then it\u2019ll return a resolved <strong>Promise<\/strong> with the result of <strong>7<\/strong>, however, we can set it to explicitly return a <strong>Promise<\/strong> like this:<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">async function evenNumber() {\r\n      return Promise.resolve(8);\r\n    }\r\n<\/code><\/pre>\n<p>Then there\u2019s the second keyword <strong>await<\/strong> that makes the function even much better.<\/p>\n<h3>Await<\/h3>\n<p>The <strong>await<\/strong> keyword simply makes JavaScript wait until that <strong>Promise<\/strong> settles and then returns its result:<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">let result = await promise;<\/code><\/pre>\n<p>Note that the <strong>await<\/strong> keyword only works inside async functions, otherwise you would get a <strong>SyntaxError<\/strong>. From the <strong>async<\/strong> function above, let\u2019s have an <strong>await<\/strong> example that resolves in 2secs.<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">async function evenNumber() {\r\n\r\n      let promise = new Promise((resolve, reject) => {\r\n        setTimeout(() => resolve(\"8\"), 2000)\r\n      });\r\n\r\n      let result = await promise; \/\/ pause till the promise resolves \r\n\r\n      alert(result); \/\/ \"8\"\r\n    }\r\n<\/code><\/pre>\n<p><strong>await<\/strong> simply makes JavaScript wait until the <strong>Promise<\/strong> settles, and then go on with the result. Meanwhile, as it waits, the engine carries on with performing other tasks like running scripts and handling events. Thus, no CPU resources will be lost.<\/p>\n<h2>Syntax<\/h2>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">async function name([param[, param[, ... param]]]) {\r\n       statements\r\n    }<\/code><\/pre>\n<h2>Return Value<\/h2>\n<p>Now that you have a fair understanding of how <strong>async\/await<\/strong> works and it\u2019s syntax, let\u2019s go ahead and dive into more awesome features that will convince you to adopt it:<\/p>\n<p><strong>Example : 2<\/strong><\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\/\/Async Await\r\n\r\n\"use strict\"\r\n\r\nfunction wait10secs(){\r\n    return new Promise((resolve)=>{\r\n        setTimeout(()=>resolve(\"waitOver\"),10000)\r\n    })\r\n}\r\n\r\nasync function callWait(){\r\n    console.log(\"Async Started\")\r\n    let result = await wait10secs(); \/\/stop execution till wait10secs is finished\r\n    console.log(\"Result:\",result)\r\n    console.log(\"Async Finished\")\r\n}\r\n\r\ncallWait()<\/code><\/pre>\n<p><strong>Example : fetch-reject-promise-and-catch-the-error-if-status-is-not-ok <\/strong><br \/>\nFetch promises only reject with a TypeError when a network error occurs. Since 4xx and 5xx responses aren&#8217;t network errors, there&#8217;s nothing to catch. You&#8217;ll need to throw an error yourself to use Promise#catch.<\/p>\n<p>A fetch Response conveniently supplies an ok , which tells you whether the request succeeded. Something like this should do the trick:<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">\r\nfunction _getSSID() {\r\n  console.log('From _getSSID')\r\n  return new Promise((resolve, reject) => {\r\n    fetch('https:\/\/jsonplaceholder.typicode.com\/posts\/1 jk')\r\n      .then(response => {\r\n        \/\/Handle Error \r\n        if(response.ok){\r\n          return response.json()\r\n        } else {\r\n          throw new Error('Something went wrong');\r\n        }\r\n      })\r\n      \/\/.then(response => {response.json()})\r\n      .then(json => resolve(json.title))\r\n      .catch((error) => { console.log('I am from reject fetch '); reject(error)})\r\n  })\r\n}\r\n\r\nasync function getSSID() {\r\n  try {\r\n    let mySSID = await _getSSID()\r\n    console.log('mySSID :', mySSID)\r\n  } catch (e) {\r\n    console.log(\"Await Error : \", e.message)\r\n  }\r\n}\r\n\r\nconsole.log('Before the Async Await')\r\ngetSSID().catch((e)=>{console.log('Error : ', e)});\r\nconsole.log('After the Async Await')\r\nconsole.log('*********************')\r\n\r\n\/\/OUTPUT\r\n\r\nBefore the Async Await\r\nFrom _getSSID\r\nAfter the Async Await\r\n*********************\r\nI am from reject fetch\r\nAwait Error :\r\nSomething went wrong\r\n<\/code><\/pre>\n<h3>Example 1 &#8211; \/\/If we use &#8220;async&#8221; keyword before the function name, it will return promise <\/h3>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">async function foo(){\r\n  return 1;\r\n}\r\nconsole.log(foo())<\/code><\/pre>\n<h3>Example 2 <\/h3>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">async function foo(){\r\n  return 1;\r\n}\r\n\r\nfoo().then(\r\n  (data)=>{console.log(data)\r\n})<\/code><\/pre>\n<h3>Example 3 &#8211; <\/br><br \/>\n\/\/ await is similar to using then in promise<br \/>\n\/\/ Can not return value from async function<br \/>\n<\/h3>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">async function foo(){\r\n\r\n  let promise = new Promise(function(resolve, reject){\r\n    setTimeout(function(){\r\n      resolve(100)\r\n    }, 1000)\r\n  })\r\n\r\n  let result = await promise;\r\n  \/\/  return result \r\n  console.log(result)\r\n}\r\nconsole.log(foo())<\/code><\/pre>\n<h3>Example 4 <\/h3>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">async function foo(){\r\n\r\n  let response = await fetch(\"https:\/\/jsonplaceholder.typicode.com\/todos\/1\")\r\n  console.log(\"response : \", response)\r\n\r\n  let result = await response.json();  \r\n  console.log(\"async : \",  result)\r\n}\r\n\r\nfoo()<\/code><\/pre>\n<h3>Example 5 &#8211; Alternet to &#8220;Ex.5&#8221;<\/h3>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">async function foo(){\r\n\r\n  let response = await fetch(\"https:\/\/jsonplaceholder.typicode.com\/todos\/1\")\r\n  console.log(\"response : \", response)\r\n\r\n  let result = await response.json();  \r\n  console.log(\"async : \",  result)\r\n\r\n  return result\r\n\r\n}\r\n\r\nfoo().then((result)=>{console.log(\"Result : \",result)});<\/code><\/pre>\n<h3>Example 6 &#8211; By default &#8220;fetch&#8221; api will return promise , we have to get through the &#8220;then&#8221; part<\/h3>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">fetch('https:\/\/jsonplaceholder.typicode.com\/todos\/1')\r\n  .then(response => response.json())\r\n  .then(json => console.log(\" fetch Api : \", json))<\/code><\/pre>\n<h3>Function returns promise object instead of value (async\/await)<\/h3>\n<p>Declare a function async means that it will return the Promise. To turn the Promise into a value, you have two options.<\/p>\n<p>The &#8220;normal&#8221; option is to use then() on it: <\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">getSSID().then(value => console.log(value));<\/code><\/pre>\n<p>You can also use await on the function:<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">const value = await getSSID();<\/code><\/pre>\n<p>The catch with using await is it too much be inside of an async function.<\/p>\n<p>At some point, you&#8217;ll have something at the top level, which can either use the first option, or can be a self-calling function like this:<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">((async () => {\r\n    const value = await getSSID();\r\n    console.log(value);\r\n})()).catch(console.error)<\/code><\/pre>\n<p>If you go with that, be sure to have a catch() on that function to catch any otherwise uncaught exceptions.<\/p>\n<p>You can&#8217;t use await at the top-level.<\/p>\n<h3>Different way of doing function call &#8211; Nested, Promise, Async\/await<\/h3>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">var fs = require('fs')\r\nvar myObj = {}\r\n\r\nfs.readFile('file1.txt', function (err, data) {\r\n  if (!err) {\r\n    myObj['data1'] = data.toString()\r\n  }\r\n})\r\n\r\nfs.readFile('file2.txt', function (err, data) {\r\n  if (!err) {\r\n    myObj['data2'] = data.toString()\r\n  }\r\n})\r\n\r\nconsole.log(myObj)\r\n\r\n\/\/2. Nested Callback\r\n\r\nvar fs = require('fs')\r\nvar myObj = {}\r\n\r\nfs.readFile('file1.txt', function (err, data) {\r\n  if (!err) {\r\n    myObj['data1'] = data.toString()\r\n    fs.readFile('file2.txt', function (err, data) {\r\n      if (!err) {\r\n        myObj['data2'] = data.toString()\r\n        console.log(myObj)\r\n      }\r\n    })\r\n  }\r\n})\r\n\r\n\/\/3. Using Promise\r\n\r\nvar fs = require('fs')\r\nvar myObj = {}\r\n\r\nfunction doA() {\r\n  return new Promise(function (resolve, reject)){\r\n    fs.readFile('file1.txt', function (err, data) {\r\n      if (!err) {\r\n        resolve(data.toString())\r\n      }\r\n    })\r\n  }\r\n}\r\n\r\nfunction doA() {\r\n  return new Promise(function (resolve, reject)){\r\n\r\n\r\n    fs.readFile('file2.txt', function (err, data) {\r\n      if (!err) {\r\n        resolve(data.toString())\r\n      }\r\n    })\r\n\r\n  }\r\n}\r\n\r\ndoA().then(function (data) {\r\n  myObj['data1'] = data;\r\n  doB().then(function (data) {\r\n    myObj['data2'] = data2\r\n    console.log(myObj)\r\n  })\r\n})\r\n\r\n\/\/3. Using Async \/ await\r\n\r\nasync function main() {\r\n  myObj['data1'] = await doA();\r\n  myObj['data2'] = await doB();\r\n  console.log(myObj)\r\n}\r\n\r\nmain()\r\n\r\n\/\/OutPut\r\n{ data1: 'This is file 1', data2: 'and thiss if file 2' }\r\n<\/code><\/pre>\n<h3>How to return values from async functions using async-await from function?<\/h3>\n<p>You cant await something outside async scope. To get expected result you should wrap your console.log into async IIFE i.e<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">async function getData() {\r\n  return await axios.get('https:\/\/jsonplaceholder.typicode.com\/posts');\r\n}\r\n\r\n(async () => {\r\n  console.log(await getData())\r\n})()<\/code><\/pre>\n<p>Since axios returns a promise the async\/await can be omitted for the getData function like so:<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">function getData() {\r\n  return axios.get('https:\/\/jsonplaceholder.typicode.com\/posts');\r\n}<\/code><\/pre>\n<p>and then do same as we did before<\/p>\n<pre class=\"line-numbers\"><code class=\"language-\">(async () => {\r\n   console.log(await getData())\r\n})()<\/code><\/pre>\n<p><a href=\"https:\/\/stackoverflow.com\/questions\/49938266\/how-to-return-values-from-async-functions-using-async-await-from-function\" rel=\"noopener\" target=\"_blank\">Ref<\/a><\/p>\n<h3 style=\"color:blue\">Reference<\/h3>\n<ol>\n<a href=\"https:\/\/javascript.info\/async-await\" rel=\"noopener\" target=\"_blank\">async-await &#8211; javascript.info<\/a><br \/>\n<a href=\"https:\/\/zellwk.com\/blog\/async-await\/\" rel=\"noopener\" target=\"_blank\">Zellwk<\/a><br \/>\n<a href=\"https:\/\/zellwk.com\/blog\/async-await-in-loops\/\" rel=\"noopener\" target=\"_blank\">JavaScript async and await in loops<\/a><br \/>\n<a href=\"https:\/\/zellwk.com\/blog\/js-promises\/\" rel=\"noopener\" target=\"_blank\">Promises <\/a><br \/>\n<a href=\"https:\/\/levelup.gitconnected.com\/async-await-vs-promises-4fe98d11038f\" rel=\"noopener\" target=\"_blank\">async-await-vs-promises<\/a><br \/>\n<a href=\"https:\/\/gist.github.com\/k-vosswinkel\/53329056e449da640b9598a6d1b8990c\" rel=\"noopener\" target=\"_blank\">Playing with promises and async\/await Code Sample<\/a><\/p>\n<li><a href=\"https:\/\/www.sitepoint.com\/javascript-goes-asynchronous-awesome\/\" rel=\"noopener\" target=\"_blank\">Sitepoint<\/a><\/li>\n<li><a href=\"https:\/\/blog.pusher.com\/promises-async-await\/\" rel=\"noopener\" target=\"_blank\">Pusher Syntax<\/a><\/li>\n<li><a href=\"https:\/\/itnext.io\/javascript-asynchronous-method-comparison-callbacks-promises-async-await-generators-e689d579aba7\" rel=\"noopener\" target=\"_blank\">Examples<\/a><\/li>\n<li><a href=\"https:\/\/codeburst.io\/javascript-es-2017-learn-async-await-by-example-48acc58bad65\" rel=\"noopener\" target=\"_blank\">Codeburst<\/a><\/li>\n<li><a href=\"https:\/\/codeburst.io\/javascript-learn-promises-f1eaa00c5461\" rel=\"noopener\" target=\"_blank\">Codeburst Promise <\/a><\/li>\n<li><a href=\"https:\/\/hackernoon.com\/understanding-async-await-in-javascript-1d81bb079b2c\" rel=\"noopener\" target=\"_blank\">hackernoon<\/a><\/li>\n<li><a href=\"https:\/\/medium.com\/@gab_montes\/is-async-await-a-step-back-to-javascript-95e31263dd31\" rel=\"noopener\" target=\"_blank\">Medium<\/a><\/li>\n<\/ol>\n<h2><a href=\"https:\/\/github.com\/kprabhanew\/ES6AsyncAwaitPromise.git\" rel=\"noopener\" target=\"_blank\" style=\"color:red\">Github<\/a><\/h2>\n","protected":false},"excerpt":{"rendered":"<p>Async\/Await Inside a function marked as async, you are allowed to place the await keyword in front of an expression that returns a Promise. When you do, the execution is paused until the Promise is resolved. Before we dive into it, let\u2019s take a moment to familiarize you with the<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[18],"tags":[98,4],"class_list":["post-313","post","type-post","status-publish","format-standard","hentry","category-javascript","tag-async","tag-javascript","ct-col-2"],"_links":{"self":[{"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/posts\/313","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/comments?post=313"}],"version-history":[{"count":14,"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/posts\/313\/revisions"}],"predecessor-version":[{"id":1840,"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/posts\/313\/revisions\/1840"}],"wp:attachment":[{"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/media?parent=313"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/categories?post=313"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/tags?post=313"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}