{"id":19091371,"url":"https://github.com/andrei-cacio/async-javascript","last_synced_at":"2025-07-19T22:06:15.177Z","repository":{"id":72353562,"uuid":"136134727","full_name":"andrei-cacio/async-javascript","owner":"andrei-cacio","description":"Basic examples of using Promises and Async/Await","archived":false,"fork":false,"pushed_at":"2018-06-26T19:15:00.000Z","size":95,"stargazers_count":2,"open_issues_count":0,"forks_count":1,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-02-22T07:27:50.783Z","etag":null,"topics":["asynchronous-programming","javascript","promise"],"latest_commit_sha":null,"homepage":null,"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/andrei-cacio.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}},"created_at":"2018-06-05T07:05:00.000Z","updated_at":"2020-11-29T20:33:40.000Z","dependencies_parsed_at":null,"dependency_job_id":"d83191a3-d5a1-43e7-abfc-8e5e355bc287","html_url":"https://github.com/andrei-cacio/async-javascript","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/andrei-cacio/async-javascript","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andrei-cacio%2Fasync-javascript","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andrei-cacio%2Fasync-javascript/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andrei-cacio%2Fasync-javascript/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andrei-cacio%2Fasync-javascript/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/andrei-cacio","download_url":"https://codeload.github.com/andrei-cacio/async-javascript/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andrei-cacio%2Fasync-javascript/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":266026375,"owners_count":23866033,"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-programming","javascript","promise"],"created_at":"2024-11-09T03:13:14.377Z","updated_at":"2025-07-19T22:06:14.739Z","avatar_url":"https://github.com/andrei-cacio.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Asynchronous Programming with Promises and Async/Await\n\nThis repo contains small exercises to get more accustom with two ways of dealing with asynchronous code in JavaScript: Promises and the new Async/Await syntax.\n\nThis repo contains four big chapters:\n\n- [Chapter 0 - The Event Loop](#chapter-0---the-event-loop)\n- [Chapter 1 - Callbacks](#chapter-1---callbacks)\n- [Chapter 2 - Promises](#chapter-2---promises9)\n- [Chapter 3 - Async/Await](#chapter-3---asyncawait)\n\nEach chapter contains exercises and questions which will walk you threw the journey from callbacks to Promises and Async/Await.\n\n## Chapter 0 - The Event Loop\n\nBefore everything, we need to talk about JavaScript's asynchronous model, or how does asynchronous programming work in JavaScript.\n\nThe most important question we will answer: **Is JavaScript an asynchronous programming language?**\n\n### JavaScript as a language\n\nWe all heard about [EcmaScript](https://www.ecma-international.org/ecma-262/8.0/index.html) right (or in its other forms: *ES5*, *ES6*, *ES2015* etc.)? EcmaScript is the standard which describes how the language should look and work. This is a very big document which contains every tiny little detail about the language: how objects intereact, what functions they should contain and how they should work etc.. This official document is written so that future JavaScript engines know how to be built. \n\nWe all heard of JavaScript engines like: Chrome's [V8](https://developers.google.com/v8), Microsoft's [ChakraCore](https://github.com/Microsoft/ChakraCore) or Mozilla's [SpiderMonkey](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey). These engines all follow the [EcmaScript](https://www.ecma-international.org/ecma-262/8.0/index.html) standard.\n\nA JavaScript engine has two important internal parts:\n\n![JavaScript Engine](./assets/JS_engine.png)\n\n- **Heap**: is the engine's memory where objects, functions etc. get allocated and managed\n- **Call Stack**: because JavaScript is single threaded, it can do only one thing at a time. The call stack manages how functions get executed, in a *LIFO* kind of fashion.\n\nFor funsies, let's open the [EcmaScript standard](https://www.ecma-international.org/ecma-262/8.0/index.html) and search for a very common function like: `setTimeout`. It should be there, right? \nNo - we will not find that function in the document. Why you ask? The answer is pretty simple. JavaScript as a language, is a synchronous programming language. However, besides JavaScript engines there is another player we need to talk about, and that player is: **JavaScript Runtimes**.\n\nA JavaScript runtime is a higher layer over the JavaScript engine which provides extra functionality like libraries, event loops etc. A few examples of runtimes are: Browsers (Chrome, Firefox etc.), NodeJS. A runtime may implement any engine it chooses. This is where the event loop is found, in the JavaScript runtime.\n\n### What is the event loop?\n\nThe Event Loop is a runtime level implementation which offers asyncrhonous code running abilities:\n\n![Event Loop Representation](./assets/JS_Runtime.png)\n\n## Chapter 1 - Callbacks\n**Callbacks** are the most *low level*ish way of handling asynchonous code. A callback is a function passed as an argument to another function. The power of this pattern kicks in when combined with an asynchronous function:\n\n```javascript\nfunction foo(callback) {\n\tsetTimeout(() =\u003e {\n\t\tcallback()\n\t}, 1000);\n}\n```\n\n### Error handling\nWe can also use callbacks to handle errors:\n\n```javascript\nfunction hello(success, failure) {\n\tsetTimeout(() =\u003e {\n\t\tconst chance = Math.ceil(Math.random() * 2);\n\n\t\tif (chance == 2) {\n\t\t\tsuccess()\n\t\t} else {\n\t\t\tfailure();\n\t\t}\n\t});\n}\n\nconst succ = () =\u003e console.log('yay!');\nconst failure = () =\u003e console.log('I should not play the Loto');\n\nhello(succ, failure);\n```\n\n\u003cdetails\u003e\u003csummary\u003eSolution example 2\u003c/summary\u003e\n\u003cp\u003e\n\t\n\t\n\tfunction all(callback, arr) {\n\t    let counter = 0;\n\t    arr.forEach(fn =\u003e fn(() =\u003e counter++));\n\n\t    const interval = setInterval(() =\u003e { \n\t      if (counter === arr.length) {\n\t\t   clearInterval(interval);\n\t\t   callback();\n\t      }\n\t    }, 250);\n\t}\n\n\tconst fn1 = cb =\u003e setTimeout(() =\u003e {\n\t   cb();\n\t}, 1000);\n\n\tconst fn2 = cb =\u003e setTimeout(() =\u003e {\n\t   cb();\n\t}, 1000);\n\n\tall(() =\u003e console.log('done'), [fn1, fn2]);\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n## Chapter 2 - Promises[[9]](https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules)\n\nWhat will be the output and why?\n\n```javascript\nconsole.log('script start');\n\nsetTimeout(function() {\n  console.log('setTimeout');\n}, 0);\n\nPromise.resolve().then(function() {\n  console.log('promise1');\n}).then(function() {\n  console.log('promise2');\n});\n\nconsole.log('script end');\n```\n\n\u003cdetails\u003e\u003csummary\u003eExplanation\u003c/summary\u003e\n\u003cp\u003e\n\nWith Promises there came a new way of executing async code called: **Microtask**. This new concept was needed because Promises can guarantee an order of execution even though they are asynchronous. This means that the event loop has another queue for scheduling these kind of microtasks. The main difference between a **task** and a **microtask** is that a task different actions can happen between them. After a task is run, the next task can only pushed to the call stack only if nothing else in mid-execution or the call stack is empty and ready to take in another task. \n\nWith **microtasks** however, they have a **priority** over tasks. If a microtask was queued, it will run before taking in any tasks. Even more, microtasks are processed as long as there are any on the microstack queue. This means that microstack processing can cause a block on the thread as long as you keep schedule them.\n\nThis can be better explained through these two examples:\n\n#### Infinite task creating is non-blocking\n\n```javascript\nfunction createTask() {\n\tconsole.log('new task');\n\tsetTimeout(createTask);\n}\t\n\ncreateTask(0);\n```\n\n#### Infinite microtask creaking blocks the main thread\n\n```javascript\nfunction createMicrotask() {\n\tconsole.log()\n\tPromise.resolve().then(createMicrotask);\n}\n\ncreateMicrotask();\n```\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n### The Event Loop with Microtasks\n\n![JavaScript Runtime Event Loop with Microtasks](./assets/JS_Runtime_with_Promises.png)\n\n\n## Chapter 3 - Async/Await\n\nThis new syntax was first introduced in [ES2017[12]](https://www.ecma-international.org/ecma-262/8.0/#sec-async-function-definitions). We now have two main players for writting asyncrhonous functions:\n\n- [`async function() {}`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)\n\tthis will create an `AsyncFunction` which returns a `Promise`.\n- [`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await)\n\tthe `await` keyword can only be used inside an `async function` (exceptions like [Chrome's DevTools](https://bugs.chromium.org/p/chromium/issues/detail?id=658558)).\n\t\n### Error handling\n\n```javascript\nconst fn = async () =\u003e Promise.reject('err');\n\nasync function foo() {\n   try {\n     fn();\n   } catch(e) {\n     console.log(e);\n   }\n}\n\nfoo();\n\n// err\n```\n## Bibliography:\n1. [Eloquent JavaScript - Chapter 11: Asynchronous Programming](https://eloquentjavascript.net/11_async.html)\n2. [MDN - Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)\n3. [MDN - async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) \n4. [JSConf EU 2014 - Philip Roberts: What the heck is the event loop anyway?](https://www.youtube.com/watch?v=8aGhZQkoFbQ)\n5. [Message Queue Wiki](https://en.wikipedia.org/wiki/Message_queue)\n6. [MDN - Concurrency model and Event Loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop)\n7. [Alexander Zlatkov - How JavaScript works: an overview of the engine, the runtime, and the call stack](https://blog.sessionstack.com/how-does-javascript-actually-work-part-1-b0bacc073cf)\n8. [How JavaScript Works: Event Loop and the rist of Async Programming](https://blog.sessionstack.com/how-javascript-works-event-loop-and-the-rise-of-async-programming-5-ways-to-better-coding-with-2f077c4438b5)\n9. [Jake Archibald - Tasks, microtasks, queues and schedules](https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/)\n10. [Jake Archibald: In The Loop - JSConf.Asia 2018](https://www.youtube.com/watch?v=cCOL7MC4Pl0)\n11. [Async/Await TC39](https://github.com/tc39/ecmascript-asyncawait)\n12. [ECMAScript® 2017 Language Specification (ECMA-262, 8th edition, June 2017)](https://www.ecma-international.org/ecma-262/8.0/#sec-async-function-definitions)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandrei-cacio%2Fasync-javascript","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fandrei-cacio%2Fasync-javascript","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandrei-cacio%2Fasync-javascript/lists"}