{"id":19624349,"url":"https://github.com/sk-azraf-sami/asynchronous-javascript","last_synced_at":"2025-07-12T07:02:07.529Z","repository":{"id":193739249,"uuid":"689032485","full_name":"Sk-Azraf-Sami/Asynchronous-JavaScript","owner":"Sk-Azraf-Sami","description":"When I start to work with React and utilizing libraries like Axios for making asynchronous HTTP requests,I realize that understanding asynchronous JavaScript is a fundamental prerequisite. I create it as my own note.","archived":false,"fork":false,"pushed_at":"2025-05-12T15:29:34.000Z","size":70,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-06-17T19:06:11.775Z","etag":null,"topics":["asynchronous-javascript","javascript","notes","synchronous"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Sk-Azraf-Sami.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2023-09-08T16:26:52.000Z","updated_at":"2025-05-12T15:29:38.000Z","dependencies_parsed_at":"2024-11-11T11:39:28.021Z","dependency_job_id":"13f8ac16-5e03-4ec6-baa9-e2d14c57d93a","html_url":"https://github.com/Sk-Azraf-Sami/Asynchronous-JavaScript","commit_stats":null,"previous_names":["sk-azraf-sami/asynchronous-javascript"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Sk-Azraf-Sami/Asynchronous-JavaScript","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Sk-Azraf-Sami%2FAsynchronous-JavaScript","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Sk-Azraf-Sami%2FAsynchronous-JavaScript/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Sk-Azraf-Sami%2FAsynchronous-JavaScript/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Sk-Azraf-Sami%2FAsynchronous-JavaScript/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Sk-Azraf-Sami","download_url":"https://codeload.github.com/Sk-Azraf-Sami/Asynchronous-JavaScript/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Sk-Azraf-Sami%2FAsynchronous-JavaScript/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":264951977,"owners_count":23687992,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["asynchronous-javascript","javascript","notes","synchronous"],"created_at":"2024-11-11T11:37:48.794Z","updated_at":"2025-07-12T07:02:07.464Z","avatar_url":"https://github.com/Sk-Azraf-Sami.png","language":"JavaScript","readme":"# Asynchronous-JavaScript\n\n## Table of Contents\n- [Example of Synchronous behaviour](#Example-of-Synchronous-behaviour)\n- [Solving above problem by using setTimeout() asynchronous function](#Solving-above-problem-by-using-setTimeout()-asynchronous-function)\n- [Callback Function](#Callback-Function)\n- [Promises](#Promises) \n- [Promise Chain](#Promise-Chain)\n- [async-await](#async-await) \n\nJavascript is a single thread language. It has synchronous blocking behaviour which makes it as a ugly language. But nowadays it becomes updated and now it has asynchronous behaviour. \n\n### [Example of Synchronous behaviour](#Example-of-Synchronous-behaviour)\n```javascript\nconst processOrder = (customer) =\u003e {\n    console.log(`Processing order for customer 1`);\n    var currentTime = new Date().getTime();\n    \n    //The loop continues to execute as long as currentTime + 3000 is greater than or equal to the current timestamp.\n    //In other words, it keeps looping until approximately 3 seconds have passed since currentTime.\n    while(currentTime + 3000 \u003e= new Date().getTime());\n    console.log(`Order processed for customer 1`);\n}\n\nconsole.log(\"Take order for customer 1\");\nprocessOrder();\nconsole.log(\"Completed order for customer 1\");\n\n/*\nOutput:\nTake order for customer 1\nProcessing order for customer 1\nOrder processed for customer 1\nCompleted order for customer 1\n*/\n```\n\n### [Solving above problem by using setTimeout() asynchronous function](#Solving-above-problem-by-using-setTimeout()-asynchronous-function)\n```javascript\nconst processOrder = (customer) =\u003e {\n    console.log(`Processing order for customer 1`);\n    var currentTime = new Date().getTime();\n\n    //here setTimeout is a asynchronous function\n    // arrow function is its callback function \n    setTimeout(()=\u003e{\n        console.log(`Cooking completed`); \n    },3000); \n    \n    console.log(`Order processed for customer 1`);\n}\n\nconsole.log(\"Take order for customer 1\");\nprocessOrder();\nconsole.log(\"Completed order for customer 1\");\n\n/*\nOutput:\nTake order for customer 1\nProcessing order for customer 1\nOrder processed for customer 1\nCompleted order for customer 1\nCooking completed\n*/\n```\n\nIn this provided code, you're using `setTimeout`, which involves several concepts related to JavaScript's asynchronous behavior: the call stack, the Web API, the callback queue, and the event loop.\n\nHere's an explanation of how these components work together in this code:\n\n1. **Call Stack**:\n   - The call stack is a data structure that keeps track of the execution of function calls in this JavaScript code. When a function is called, it's pushed onto the stack, and when it returns, it's popped off the stack.\n\n   In this code:\n   - When you call `processOrder()`, it's added to the call stack.\n   - `console.log(\"Take order for customer 1\");` and `console.log(\"Completed order for customer 1\");` are also added to the call stack as they are encountered in the code.\n\n2. **Web API**:\n   - The `setTimeout` function is part of the Web API in the browser environment. Web APIs provide functionality that is not directly handled by JavaScript itself, such as timers, making HTTP requests, and interacting with the DOM.\n\n   In this code:\n   - When you execute `setTimeout`, it sets a timer for 3000 milliseconds but doesn't block the call stack. Instead, it hands off the callback function (the one logging \"Cooking completed\") to the Web API.\n\n3. **Callback Queue**:\n   - When the timer in `setTimeout` expires (in this case, after 3000 milliseconds), the callback function is placed in the callback queue.\n\n   In this code:\n   - After approximately 3 seconds, \"Cooking completed\" is placed in the callback queue.\n\n4. **Event Loop**:\n   - The event loop is responsible for constantly checking the callback queue for completed tasks and moving them to the call stack when it's empty. This ensures that asynchronous code, like the callback in `setTimeout`, is executed when its conditions are met without blocking the main thread.\n\n   In this code:\n   - The event loop monitors the callback queue and, after the 3000ms timer expires, moves the \"Cooking completed\" callback function from the queue to the call stack. It's then executed.\n\nHere's the sequence of events:\n\n1. \"Take order for customer 1\" is logged.\n2. `processOrder()` is called and added to the call stack.\n3. `console.log(\"Processing order for customer 1\");` is logged.\n4. `setTimeout` is called and schedules the \"Cooking completed\" callback function to run after 3000 milliseconds but does not block the call stack.\n5. `console.log(\"Order processed for customer 1\");` is logged.\n6. The call stack is empty.\n7. The event loop detects that the callback queue contains the \"Cooking completed\" callback, so it moves it to the call stack.\n8. \"Cooking completed\" is logged.\n\nThis demonstrates how JavaScript's asynchronous behavior and the event loop allow non-blocking execution of code, like the delayed callback in `setTimeout.\n\n### [Callback Function](#Callback-Function)\nBut for above solution there is a problem of workflow control. We can control the workflow of code by implementation of callback function.\n\n```javascript\nconst takeOrder = (customer,callback) =\u003e {\n    console.log(`Take order for ${customer}`);\n    callback(customer);\n};\n\nconst processOrder = (customer,callback) =\u003e {\n    console.log(`Process order for ${customer}`);\n    setTimeout(() =\u003e {\n        console.log(`Cooking completed`);\n        console.log(`Order processed for ${customer}`);\n        callback(customer); \n    }, 3000);\n};\n\nconst completeOrder = (customer) =\u003e {\n    console.log(`Completed order for ${customer}`);\n};\n\n// call function \n// takeOrder function call processOrder function \n// processOrder function call completeOrder function \ntakeOrder('customer 1',(customer)=\u003e{\n    processOrder(customer,(customer) =\u003e {\n        completeOrder(customer);\n    });\n}); \n\n/*\nOutput: \nTake order for customer 1\nProcess order for customer 1\nCooking completed\nOrder processed for customer 1\nCompleted order for customer 1\n*/\n```\n\n**Is this process really asynchronous?**\n```javascript\nconst takeOrder = (customer,callback) =\u003e {\n    console.log(`Take order for ${customer}`);\n    callback(customer);\n};\n\nconst processOrder = (customer,callback) =\u003e {\n    console.log(`Process order for ${customer}`);\n    setTimeout(() =\u003e {\n        console.log(`Cooking completed`);\n        console.log(`Order processed for ${customer}`);\n        callback(customer); \n    }, 3000);\n};\n\nconst completeOrder = (customer) =\u003e {\n    console.log(`Completed order for ${customer}`);\n};\n\n// call function \n// takeOrder function call processOrder function \n// processOrder function call completeOrder function \ntakeOrder('customer 1',(customer)=\u003e{\n    processOrder(customer,(customer) =\u003e {\n        completeOrder(customer);\n    });\n}); \n\n//This line will run middle of asynchronus execution \nconsole.log('Hello'); \n\n/*\nOutput: \nTake order for customer 1\nProcess order for customer 1\nHello\nCooking completed\nOrder processed for customer 1\nCompleted order for customer 1\n*/\n```\n### [Promises:](#Promises) \nBy using promise, callback function become more readable and we can solve the 'callback hell' problem.\n```javascript\nconst hasMeeting = false;\nconst meeting = new Promise((resolve, reject) =\u003e {\n    if(hasMeeting == false){\n        const meetingDetails = {\n            name: \"Project Meeting\",\n            location: \"Google Meeet\",\n            time: \"10:00 PM\"\n        };\n        \n        resolve(meetingDetails);\n    }\n    \n    else{\n        reject(new Error(\"Meeting already scheduled!!\"));\n    }\n});\n\nmeeting\n    .then((res) =\u003e {\n        // resolve data\n        console.log(JSON.stringify(res))\n    })\n    .catch((err) =\u003e {\n        //rejected data\n        console.log(err.message);\n    })\n\n/*\nOutput (if hasMeeting=false): \n{\"name\":\"Project Meeting\",\"location\":\"Google Meeet\",\"time\":\"10:00 PM\"}\n\n*****************************************************************\n\nOutput (if hasMeeting=true: \nMeeting already scheduled!!\n\n******************************************************************\n\n*/\n\n```\n\nIn 'promise' callback function is used which holds two function 'resolve' and 'reject'. Now above code is more readable than direct using of 'callback' function.\n\n**Is it really asynchronous?**\n```javascript\nconst hasMeeting = true;\nconst meeting = new Promise((resolve, reject) =\u003e {\n    if(hasMeeting == false){\n        const meetingDetails = {\n            name: \"Project Meeting\",\n            location: \"Google Meeet\",\n            time: \"10:00 PM\"\n        };\n        \n        resolve(meetingDetails);\n    }\n    \n    else{\n        reject(new Error(\"Meeting already scheduled!!\"));\n    }\n});\n\nmeetinge \n    .then((res) =\u003e {\n        // resolve data\n        console.log(JSON.stringify(res))\n    })\n    .catch((err) =\u003e {\n        //rejected data\n        console.log(err.message);\n    })\n\nconsole.log(\"Hello\");\n/*\nOutput (if hasMeeting=false): \nHello\n{\"name\":\"Project Meeting\",\"location\":\"Google Meeet\",\"time\":\"10:00 PM\"}\n\n*****************************************************************\n\nOutput (if hasMeeting=true: \nHello\nMeeting already scheduled!!\n\n******************************************************************\n\n*/\n\n```\nWe don't assign any delay to the 'promise' but first `Hello` is printed! Then the promise will be executed. \n\n### [Promise Chain](#Promise-Chain)\n```javascript\nconst hasMeeting = false;\nconst meeting = new Promise((resolve, reject) =\u003e {\n    if(hasMeeting == false){\n        const meetingDetails = {\n            name: \"Project Meeting\",\n            location: \"Google Meeet\",\n            time: \"10:00 PM\"\n        };\n        \n        resolve(meetingDetails);\n    }\n    \n    else{\n        reject(new Error(\"Meeting already scheduled!!\"));\n    }\n});\n\n// 2nd promise \nconst addToCalendar = (meetingDetails) =\u003e {\n    return new Promise((resolve, reject) =\u003e {\n        const calendar = `${meetingDetails.name} is scheduled on ${meetingDetails.location} at ${meetingDetails.time}`;\n        resolve(calendar)\n    })\n}\n\n// there is no reject \n// so we can create addToCalendar function like this also \n/*const addToCalendar = (meetingDetails) =\u003e {\n     const calendar = `${meetingDetails.name} is scheduled on ${meetingDetails.location} at ${meetingDetails.time}`;\n    return Promise.resolve(calendar)\n}*/\n\n// we can handle multiple then by using single catch \nmeeting\n    .then(addToCalendar)\n    .then((res) =\u003e {\n        // resolve data\n        // now calendar in the resolve \n        // so, resolve that means calendar will be printed\n        console.log(res)\n    })\n    .catch((err) =\u003e {\n        //rejected data\n        console.log(err.message);\n    })\n\nconsole.log(\"Hello\");\n/*\nHello\nProject Meeting is scheduled on Google Meeet at 10:00 PM\n*/\n\n```\n\n**In this example:**\n\n```javascript\nconst promise1 = Promise.resolve(`Promise 1 resolved`);\nconst promise2 = new Promise((resolve, reject) =\u003e {\n    setTimeout(() =\u003e {\n        resolve(`Promise 2 resolved`)\n    }, 2000);\n});\n\npromise1.then((res) =\u003e {\n    console.log(res)\n});\n\npromise2.then((res) =\u003e {\n    console.log(res)\n})\n\n/*\nOutput: \nPromise 1 resolved\nPromise 2 resolved\n*/\n```\nAfter 'promise1' is resolved, 'promise2' will be resolved after 2 seconds. \u003cbr\u003e\nBut we can solve this problem by concurrently run these promises.\n\n**Promise.all**\n\n```javascript\nconst promise1 = Promise.resolve(`Promise 1 resolved`);\nconst promise2 = new Promise((resolve, reject) =\u003e {\n    setTimeout(() =\u003e {\n        resolve(`Promise 2 resolved`)\n    }, 2000);\n});\n\n// creating array of two promises\nPromise.all([promise1,promise2]).then((res) =\u003e {\n    console.log(res)\n})\n\n/*\nOutput: \n[ 'Promise 1 resolved', 'Promise 2 resolved' ]\n*/\n```\nAfter 2 seconds, both promise1 and promise2 run together. \n\n**Promise.race**\n```javascript\nconst promise1 = Promise.resolve(`Promise 1 resolved`);\nconst promise2 = new Promise((resolve, reject) =\u003e {\n    setTimeout(() =\u003e {\n        resolve(`Promise 2 resolved`)\n    }, 2000);\n});\n\n// creating array of two promises\n// race between two promises\n// two promise will be start executing at the same time\n// one promise will be printed which win this race\nPromise.race([promise1,promise2]).then((res) =\u003e {\n    console.log(res)\n})\n\n/*\nOutput: \nPromise 1 resolved\n*/\n```\n**Another Example**\n\n```javascript\nconst promise1 = new Promise((resolve, reject) =\u003e {\n    setTimeout(() =\u003e {\n        resolve(`promise1 resolved`);\n    }, 5000);\n});\n\nconst promise2 = new Promise((resolve, reject) =\u003e {\n    setTimeout(() =\u003e {\n        resolve(`promise2 resolved`)\n    }, 2000);\n}); \n\nPromise.race([promise1, promise2]).then((res) =\u003e {\n    console.log(res)\n})\n\n/*\nOutput: \npromise2 resolved\n*/\n```\n\nBut way of `promise` call is not so much programming friendly. \n\n### [async-await](#async-await) \n\n```javascript\n// this is synchronous function \nfunction test(){\n    return `Hello`;\n}\nconsole.log(test()); \n\n// make test() function asynchronous\nfunction test2(){\n    return Promise.resolve(`Hello`);\n}\nconsole.log(test2());\n\n// do the same thing by using 'async'\nasync function test3(){\n    return `Hello`; \n}\nconsole.log(test3());\n\n/*\nOutput: \nHello\nPromise { 'Hello' }\nPromise { 'Hello' }\n*/\n```\n`await` can't use in normal function. \u003cbr\u003e\nAlways `await` use in `async` function. \n\n```javascript\nconst hasMeeting = false;\nconst meeting = new Promise((resolve, reject) =\u003e {\n    if(hasMeeting == false){\n        const meetingDetails = {\n            name: \"Project Meeting\",\n            location: \"Google Meeet\",\n            time: \"10:00 PM\"\n        };\n        \n        resolve(meetingDetails);\n    }\n    \n    else{\n        reject(new Error(\"Meeting already scheduled!!\"));\n    }\n});\n\n// 2nd promise \nconst addToCalendar = (meetingDetails) =\u003e {\n     const calendar = `${meetingDetails.name} is scheduled on ${meetingDetails.location} at ${meetingDetails.time}`;\n    return Promise.resolve(calendar)\n}\n\n// we can handle multiple then by using single catch \n// don't need to use .then .catch\nasync function myMeeting(){\n    try{\n      const meetingInfo = await meeting;\n      const calendarInfo = await addToCalendar(meetingInfo);\n      console.log(calendarInfo);\n    }\n    catch(error) {\n        console.log(\"Something is wrong here!\", error.message);\n    }\n}\n\nmyMeeting();\n\nconsole.log(\"Hello\");\n/*\nHello\nProject Meeting is scheduled on Google Meeet at 10:00 PM\n*/\n\n```\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsk-azraf-sami%2Fasynchronous-javascript","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsk-azraf-sami%2Fasynchronous-javascript","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsk-azraf-sami%2Fasynchronous-javascript/lists"}