Showcasing the asynchronous programming features of JavaScript.
JavaScript has a rich set of options when it comes to asynchronous programming. This project is a collection of examples that show how to use these features.
There are four sample programs that print messages interspersed with asynchronous "sleep" operations. Each program has the exact same output but is implemented in a unique style. Read the code and the comments carefully and then follow the instructions below to run the programs.
Follow these instructions to run the example programs.
- Pre-requisite: Node.js
- I used version 18.12.1
- Run the traditional callback-based program:
-
node timeout-with-callbacks.mjs
-
- Next, run the promise-based program:
-
node timeout-with-promises.mjs
-
- Next, run the generator-based program:
-
node timeout-with-generators.mjs
-
- Finally, run the async/await-based program:
-
node timeout-with-async-await.mjs
-
- Experiment!
- Change the code, re-run the programs, and think critically so you can learn these JavaScript features "in your bones".
- MDN Reference Docs: *function
The
function*
declaration (function
keyword followed by an asterisk) defines a generator function, which returns aGenerator
object. Generators in JavaScript — especially when combined with Promises — are a very powerful tool for asynchronous programming as they mitigate — if not entirely eliminate -- the problems with callbacks, such as Callback Hell and Inversion of Control. However, an even simpler solution to these problems can be achieved with async functions.- Is this MDN doc saying that generator functions are obsoleted by
async
functions? Very interesting.
- Is this MDN doc saying that generator functions are obsoleted by
- MDN Reference Docs: async function
The
async function
declaration declares an async function where theawait
keyword is permitted within the function body. Theasync
andawait
keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.