{"flag":true,"single":true,"pageTitle":"Async await in Javascript ||Sync, Async, Callback, Promise, Aync await, Fetch Api","post":{"id":288,"user_id":"1","slug":"async-await-in-javascript-lezr","title":"Async await in Javascript ||Sync, Async, Callback, Promise, Aync await, Fetch Api","body":"<p><strong>Sync:<\/strong><\/p>\r\n<p>Code run in sequence, Each next instruction wait to execute Next one.<\/p>\r\n<pre class=\"language-markup\"><code>Console.log(\"1\");\r\nConsole.log(\"2\");\r\nConsole.log(\"3\");<\/code><\/pre>\r\n<p>Output:&nbsp;<\/p>\r\n<p>1<br>2<br>3<\/p>\r\n<p><strong>Async:<\/strong><br>Execute Next instruction immediately without blockig the flow, for Async we use <strong>setTimeout <\/strong>function<\/p>\r\n<pre class=\"language-markup\"><code>setTimeout(hello,2000); \/\/ it will execute any given function with given time.\r\nfunction hello(){\r\n    console.log(\"I will be executed after 2 seconds\");\r\n}<\/code><\/pre>\r\n<p>The above code is equal to&nbsp;<\/p>\r\n<pre class=\"language-markup\"><code>setTimeout(()=&gt;{\r\n    console.log(\"I will be executed after 2 seconds\");\r\n},2000);<\/code><\/pre>\r\n<p>Also this one<\/p>\r\n<pre class=\"language-markup\"><code>setTimeout(hello,2000);\r\nconst hello = ()=&gt;{  \/\/arrow function to a variable\r\n    console.log(\"I will be executed after 2 seconds\");\r\n}<\/code><\/pre>\r\n<p><strong>Now if we put<\/strong><\/p>\r\n<table style=\"border-collapse: collapse; width: 100.032%;\" border=\"1\"><colgroup><col style=\"width: 49.9636%;\"><col style=\"width: 49.9636%;\"><\/colgroup>\r\n<tbody>\r\n<tr>\r\n<td>\r\n<pre class=\"language-markup\"><code>console.log(1);\r\nconsole.log(2);\r\nsetTimeout(\r\n    ()=&gt;{ console.log(\"xd\"); }\r\n    ,4000\r\n );\r\nconsole.log(3);<\/code><\/pre>\r\n<\/td>\r\n<td>\r\n<p><strong>Output:<\/strong><br>1<\/p>\r\n<p>2<\/p>\r\n<p>3 \/\/don't wait for xd output, because this is async<\/p>\r\n<p>xd \/\/after 4 seconds<\/p>\r\n<\/td>\r\n<\/tr>\r\n<\/tbody>\r\n<\/table>\r\n<p>&nbsp;<\/p>\r\n<p><strong>CallBack:<br><\/strong>A function passed in another as argument<\/p>\r\n<table style=\"border-collapse: collapse; width: 100.032%;\" border=\"1\"><colgroup><col style=\"width: 49.9636%;\"><col style=\"width: 49.9636%;\"><\/colgroup>\r\n<tbody>\r\n<tr>\r\n<td>\r\n<pre class=\"language-markup\"><code>function calculator(a,b,DoSum){\r\n    DoSum(a,b);\r\n}<\/code><\/pre>\r\n<\/td>\r\n<td>\r\n<pre class=\"language-markup\"><code>function sum(a,b){\r\n    console.log(a+b);\r\n}<\/code><\/pre>\r\n<\/td>\r\n<\/tr>\r\n<\/tbody>\r\n<\/table>\r\n<p>So now Call calculator(1,2,<strong>sum<\/strong>); \/\/inside calculator DoSum is replaced by sum and sum function is called, so we can use any parameter in place of DoSum<\/p>\r\n<p><strong>*********<em> CallBack Hell *******<br><\/em><\/strong>Let suppose we want to get a data and if returned our data then send 2nd request then 3rd then ....<\/p>\r\n<p>we use code below&nbsp;<br>Real case example will be (if username exist, then check password, if password and user matched then check for 2fa)<strong><br><\/strong><\/p>\r\n<pre class=\"language-markup\"><code>function getData(dataId, getNextData) {   \/\/ Simulate data retrieval with a 2-second delay\r\n        setTimeout(() =&gt; {\r\n            console.log(\"data\", dataId);\r\n            if (getNextData) {\r\n                getNextData();\r\n            }\r\n        }, 2000);\r\n    }\r\n    \/\/getData(1); \/\/ if condition is not executed, \r\n\r\n    \/\/ Callback hell example\r\ngetData(1, () =&gt; {   \r\n        \/\/getData(1, getData(2)); we can't use like this so we use arrow functions\r\n        console.log(\"getting data2 ....\");\r\n        getData(2, () =&gt; {\r\n            console.log(\"getting data3 ....\");\r\n            getData(3, () =&gt; {\r\n                console.log(\"getting data4 ....\");\r\n                getData(4);\r\n            });\r\n        });\r\n    });<\/code><\/pre>\r\n<p><strong>************ Promise **********<\/strong><br>&nbsp; &nbsp; <strong>*<\/strong> To solve call back hell we use promise<br>&nbsp; &nbsp; <strong>*<\/strong> Promise is promise for completion of task. It is an object<br>&nbsp; &nbsp; <strong>*<\/strong> It has 3 states, <strong>pending, fulfilled, rejected<\/strong><br>&nbsp; &nbsp; <strong>*<\/strong> if <strong>resolve()<\/strong> function run promise is <strong>fulfilled<\/strong>, if <strong>reject <\/strong>function run promise is <strong>rejected <\/strong>else <strong>pending<\/strong><\/p>\r\n<p><strong>Pending state<\/strong><\/p>\r\n<pre class=\"language-markup\"><code>let my_promise = new Promise((resolve,reject)=&gt;{\r\n        console.log(\"promise\"); \r\n       \/\/in console type my_promise and check its state (its pending)\r\n});<\/code><\/pre>\r\n<p><strong>Resolved State:<br><\/strong><\/p>\r\n<pre class=\"language-markup\"><code>let my_promise_resolved = new Promise((resolve,reject)=&gt;{\r\n        resolve(123); \/\/resolve definition created by js internally\r\n        console.log(\"my_promise_resolved\"); \r\n        \/\/in console type my_promise_resolved and check its state (its fulfilled)\r\n});<\/code><\/pre>\r\n<p><strong>Rejected Proxy<\/strong><\/p>\r\n<pre class=\"language-markup\"><code>let my_promise_rejected = new Promise((resolve,reject)=&gt;{\r\n        reject(\"Error: rejected item\"); \/\/resolve is created by js internally\r\n        console.log(\"my_promise_rejected\"); \r\n        \/\/in console type my_promise_resolved and check its state (its fulfilled)\r\n});<\/code><\/pre>\r\n<p>&nbsp; &nbsp; <strong>*<\/strong> How we use <strong>promise <\/strong>if we get promise from some <strong>API <\/strong>etc&nbsp;<br>&nbsp; &nbsp; <strong>*<\/strong> <strong>promise.then() <\/strong>is used when promise is fulfilled<br>&nbsp; &nbsp; <strong>*<\/strong> <strong>promise.catch()<\/strong> is used when promise failed&nbsp;<br>&nbsp; &nbsp; <strong>*<\/strong> see examples below, we can use a parameter to get &nbsp;<strong>PromiseResult <\/strong>generated by <strong>resolve <\/strong>or <strong>reject <\/strong>function<\/p>\r\n<p><strong>Resolved Proxy<\/strong><\/p>\r\n<pre class=\"language-markup\"><code>my_promise_resolved.then(()=&gt;{\r\n    console.log(\"wao my promise is fullfiled\");\r\n});<\/code><\/pre>\r\n<p><strong>Resolved Proxy WITH PromiseResult<\/strong><\/p>\r\n<pre class=\"language-markup\"><code>my_promise_resolved.then((resu)=&gt;{\r\n    console.log(\"wao my promise is fullfiled\",resu);\r\n});<\/code><\/pre>\r\n<p><strong>Rejected promise with&nbsp;PromiseResult<\/strong><\/p>\r\n<pre class=\"language-markup\"><code>my_promise_resolved.catch((resu)=&gt;{\r\n    console.log(\"oh hu failed\",resu);\r\n});<\/code><\/pre>\r\n<p><strong>************ Promise chaining&nbsp;************ <br><\/strong>let suppose a <strong>async<\/strong> function returen <strong>promise <\/strong>with 4 seconds delay ie <strong>asyncFunc&nbsp;<\/strong>and we want to get someother data after getting previous one successfully we use <strong>promise.then<\/strong> inside <strong>promise.then<br><\/strong><\/p>\r\n<table style=\"border-collapse: collapse; width: 100.032%; height: 263.906px;\" border=\"1\"><colgroup><col style=\"width: 51.4544%;\"><col style=\"width: 48.5392%;\"><\/colgroup>\r\n<tbody>\r\n<tr style=\"height: 263.906px;\">\r\n<td style=\"height: 263.906px;\">\r\n<pre class=\"language-markup\"><code>function asyncFunc(){ \/\/think some api return you promise\r\n        return new Promise((resolve,reject)=&gt;{\r\n            setTimeout(()=&gt;{\r\n                console.log(\"some data\");\r\n                resolve(\"success\");\r\n            },4000);\r\n        });\r\n}<\/code><\/pre>\r\n<\/td>\r\n<td style=\"height: 263.906px;\">\r\n<pre class=\"language-markup\"><code>let p1 = asyncFunc(); \r\n    p1.then((res)=&gt;{ \/\/you are handling promise\r\n        console.log(\"p1::: \",res);\r\n        \/\/ geting more data using chaining so first solve p1, then p2\r\n        let p2 = asyncFunc();\r\n        p2.then((res)=&gt;{\r\n            console.log(\"p2::: \",res);\r\n        });\r\n});<\/code><\/pre>\r\n<\/td>\r\n<\/tr>\r\n<\/tbody>\r\n<\/table>\r\n<p>We can make it simple also AND NOW compare it &nbsp;with callback hell, its easy then that&nbsp;<\/p>\r\n<pre class=\"language-markup\"><code>asyncFunc().then((res)=&gt;{ \r\n        console.log(\"p1 SIMPLE CODE::: \",res);\r\n        asyncFunc().then((res)=&gt;{\r\n            console.log(\"p2 SIMPLE CODE::: \",res);\r\n        });\r\n});<\/code><\/pre>\r\n<p><strong>************&nbsp; ASYNC, AWAIT ************ <\/strong><\/p>\r\n<p>BUT THIS IS ALSO DIFFICULT, WE USE ASYNC, AWAIT<br>&gt; <strong>async <\/strong>function <strong>always return a promise<\/strong> , no need to handle promise manually<br>&gt; <strong>await<\/strong>, its wait untill function return promise<br>&gt; but await is only used inside aync functions, ie we used below exe function<\/p>\r\n<table style=\"border-collapse: collapse; width: 100.032%;\" border=\"1\"><colgroup><col style=\"width: 49.9636%;\"><col style=\"width: 49.9636%;\"><\/colgroup>\r\n<tbody>\r\n<tr>\r\n<td>\r\n<pre class=\"language-markup\"><code>function api(){\r\n    return new Promise((resolve,reject)=&gt;{\r\n        setTimeout(()=&gt;{\r\n            console.log(\"hello\");\r\n            resolve(200);\r\n        },2000);\r\n    });\r\n}<\/code><\/pre>\r\n<\/td>\r\n<td>\r\n<pre class=\"language-markup\"><code> \/\/ await api(); it is wrong\r\nasync function exe(){ \/\/in console execute it like exe()\r\n    await api();\r\n    await api();\r\n}<\/code><\/pre>\r\n<\/td>\r\n<\/tr>\r\n<\/tbody>\r\n<\/table>\r\n<p>In callback hell, promise, promise chaining we don't need extra function , but in async await, we need to define extra function&nbsp;<br>To prevent it we use IIFE, Immediate invoked function execution<\/p>\r\n<pre class=\"language-markup\"><code>\/***** IIFE ********\/\r\n(async function(){ \/\/ no need to run exe() in console\r\n    await api(); \r\n    await api();\r\n})();<\/code><\/pre>\r\n<p>&nbsp;<\/p>\r\n<p><strong>FETCH API: No need ajax requests anymore<\/strong><\/p>\r\n<p>Fetch api always return promise<\/p>\r\n<p>&nbsp;<\/p>\r\n<pre class=\"language-markup\"><code>const get_data = async ()=&gt;{\r\n    console.log(\"getting data\");\r\n   var responce = await fetch(\"https:\/\/jsonplaceholder.typicode.com\/posts\/1\"); \/\/return 1st response promise\r\n   var actual_data = await responce.json(); \/\/2ND responce\r\n    console.log(responce); \r\n    console.log(actual_data); \r\n}<\/code><\/pre>\r\n<p><strong>POST REQUEST:<\/strong><\/p>\r\n<pre class=\"language-markup\"><code>const response = await fetch(\"https:\/\/example.org\/post\", {\r\n  method: \"POST\",\r\n  \/\/ ...\r\n});<\/code><\/pre>\r\n<p>HEADERS:<\/p>\r\n<pre class=\"language-markup\"><code>const response = await fetch(\"https:\/\/example.org\/post\", {\r\n  headers: {\r\n    \"Content-Type\": \"application\/json\",\r\n  },\r\n  \/\/ ...\r\n});<\/code><\/pre>\r\n<p>Cancel request:<\/p>\r\n<pre class=\"language-markup\"><code>const controller = new AbortController();\r\n\r\nconst fetchButton = document.querySelector(\"#fetch\");\r\nfetchButton.addEventListener(\"click\", async () =&gt; {\r\n  try {\r\n    console.log(\"Starting fetch\");\r\n    const response = await fetch(\"https:\/\/example.org\/get\", {\r\n      signal: controller.signal,\r\n    });\r\n    console.log(`Response: ${response.status}`);\r\n  } catch (e) {\r\n    console.error(`Error: ${e}`);\r\n  }\r\n});\r\n\r\nconst cancelButton = document.querySelector(\"#cancel\");\r\ncancelButton.addEventListener(\"click\", () =&gt; {\r\n  controller.abort();\r\n  console.log(\"Canceled fetch\");\r\n});<\/code><\/pre>","category_id":"12","is_private":"0","created_at":"2025-01-27T11:23:39.000000Z","updated_at":"2025-01-29T11:13:24.000000Z","category":{"id":12,"user_id":"1","name":"Javascript","slug":"javascript-xplw","parent_id":null,"created_at":"2023-03-23T02:24:43.000000Z","updated_at":"2023-03-23T02:24:43.000000Z"},"user":{"id":1,"name":"R GONDAL","email":"rizikmw@gmail.com","email_verified_at":null,"two_factor_confirmed_at":null,"current_team_id":"1","profile_photo_path":null,"created_at":"2023-03-12T10:49:33.000000Z","updated_at":"2025-01-10T12:59:00.000000Z","profile_photo_url":"https:\/\/ui-avatars.com\/api\/?name=R+G&color=7F9CF5&background=EBF4FF"}},"pageDesc":"Sync: Code run in sequence, Each next instruction wait to execute Next one. Console.log(\"1\"); Console.log(\"2\"); Console.log(\"3\"); Output:&nb - Async await in Javascript ||Sync, Async, Callback, Promise, Aync await, Fetch Api (Updated: January 29, 2025) - Read more about Async await in Javascript ||Sync, Async, Callback, Promise, Aync await, Fetch Api at my programming site [SITE]","categories":[]}