Episode 2 - Easy writing async javascript
Reviewing the Previous Chapter
We now know that asynchronous code relies on APIs provided by the runtime environment (browsers, Node.js) to handle multiple tasks concurrently. The conclusion is simple: The JavaScript engine can—and does—execute only one task at a time, but the runtime environment provides ways for JavaScript to run asynchronously. Here is a simple exercise to test your understanding of the previous article:
// The cat meowsfunction cat() { console.log('🐱');}
// The dog barks (after 0 milliseconds)function dog() { setTimeout(() => { console.log('🐶'); }, 0);}
// The human says hellofunction human() { console.log('✋🏻');}
// What is the output order?cat();dog();human();The functions are called in this order: cat > dog > human. Based on the order and what the code appears to do, you might expect the output to be: 🐱 > 🐶 > ✋🏻,
but the actual answer is: 🐱 > ✋🏻 > 🐶. This is because setTimeout inside the dog function is asynchronous. Its callback is placed in the Callback Queue and waits until all the work currently on the Call Stack has finished before it can execute. In the meantime, the remaining work on the main thread continues, producing ✋🏻 before 🐶. If you fully understand this concept, congratulations—you are ready to dive deeper into writing asynchronous code!
Writing Asynchronous Code in Practice
The previous example is very simple: at most, it schedules some code to run after a specified delay. Real-world situations are often much more complicated, such as:
- Fetching data with uncertain timing or outcomes (AJAX)
- Performing time-consuming work that blocks other code from running (Thread Blocking)
In these situations, you need to consider error handling and execution order. A good approach to asynchronous programming makes code easier to read and maintain while helping you handle asynchronous operations more effectively. We will work through the following topics, from basic to advanced:
- Callbacks
- Promises and their methods
- Async / Await
We will write practical examples and discuss the strengths and caveats of each approach 😊. Throughout the examples, we will use the following simple function as a starting point and try different ways of rewriting it.
// Description: This synchronous function calculates the area of a square (side × side)// We will use this simple example as a template and rewrite it as asynchronous code// Requirement: Calculate the area of a square, but wait 1 second before returning the result
function getSquareArea(side) { return side * side;}
getSquareArea(2); // 4Callbacks
Why use callbacks?
What do callbacks have to do with learning asynchronous programming?
Think about commonly used methods such as addEventListener and setTimeout: both take a function as an argument that wraps the work to perform when an asynchronous event occurs:
<button>Click me to trigger an event👆🏻</button>
<script> const button = document.querySelector(button); button.addEventListener('click', function (event) { console.log(event); alert(`You clicked the button! Open the browser console to see the result.`); });</script>Callbacks let you wrap asynchronous code in a function and execute it after an asynchronous event occurs. Rewriting our square-area calculation, we can pass the corresponding result to the callback on success or failure:
function getRectangleArea(side, callback) { // Define an error condition: not a number if (typeof side !== 'number') { callback(new TypeError('Please enter a number')); return; } // Define an error condition: not a positive number if (side <= 0) { callback(new Error('Please enter a positive number')); return; } // Perform an asynchronous operation and execute the callback after the asynchronous event occurs setTimeout(() => callback(null, side ** 2), 1000);}
getRectangleArea(2, (error, result) => { // Any error will be handled here if (error !== null) { console.error(error); return; } console.log(result);});That is the basic idea behind callbacks. Let us summarize their characteristics:
- Pro - No abstract wrapper; conceptually, they are just functions, making them easy to understand.
- Pro - Their structure resembles synchronous code.
- Con - Execution order is not intuitive, and callbacks can easily become deeply nested (callback hell).
- Con - They introduce Inversion of Control.
- Con - There is no standardized format for writing them.
Promise
The previous approach has significant drawbacks: its lack of structure can lead to messy code that is difficult to read and write. To address these issues, JavaScript introduced Promises in ES6, “wrapping asynchronous code in an object” and providing a “standardized” way to handle asynchronous code. This object has two properties: state and result.
- State: A Promise object can be in only one of three states:
Pending- The initial state; the asynchronous operation has not completedFulfilled- The asynchronous code executed successfullyRejected- The asynchronous code failed
- Result: A Promise object can have one of two outcomes:
resolve- Successreject- Failure
Let us create a new Promise to see how it works:
// You can choose any names for resolve and rejectconst promise = new Promise((resolve, reject) => { // Some asynchronous code if (/* Check the result */){ resolve(value); } else { reject(error); }});As you can see, the callback passed to the Promise takes two parameters: the functions to call on success and failure. We can easily define the success and failure conditions within this Promise object. In the following example, we simply call resolve on success and reject on failure:
// Promise to return a result after 1 second: reject on error, or resolve with the result on successfunction getRectangleArea(side) { return new Promise((resolve, reject) => { if (typeof side !== 'number') { reject(new TypeError('Please enter a number')); return; }
if (side <= 0) { reject(new Error('Please enter a positive number')); return; } setTimeout(() => { resolve(side ** 2); }, 1000); });}We have now successfully replaced the callback with a Promise object. But once we have a Promise, how do we use it? Can we access its value directly in synchronous code? No: while the asynchronous operation is still in progress, the Promise is in the Pending state. Accessing the Promise directly cannot retrieve its future value.
// Simply retrieving the Promise object in synchronous code does not give us the resultconsole.log(getRectangleArea(2));How Do We Retrieve the Value of a Promise?
We can use the Promise.then method to handle success and failure once the Promise settles:
Promise.then(success, error);More commonly, .catch is used to handle errors. There are some subtle differences between the two approaches, but .catch provides more comprehensive and intuitive error handling. This is the recommended approach in most cases:
Promise.then(success).catch(error);Applying this to our earlier example, we can handle the Promise object returned by getRectangleArea as follows:
getRectangleArea(2) .then((result) => { console.log(result); }) .catch((error) => { console.error(error); });That is the basic idea behind Promises. Let us summarize their characteristics:
- Pro - Better readability.
- Pro - A consistent format.
- Pro - Better error handling and many additional methods for handling asynchronous operations (such as Promise.all).
- Con - They can return only one value at a time.
- Con - Older browsers do not support Promises.
Async / Await
Async Await was added to JavaScript in ES2017. Built on top of Promises, it provides more concise syntax for handling asynchronous operations, allowing us to write asynchronous code as though it were synchronous.
Async
The async keyword tells the JavaScript engine that we are defining an asynchronous function and makes the function return a Promise object.
Await
The await keyword can only be used inside an async function. Placing it before a Promise lets us wait for that Promise to resolve and retrieve its value.
async function asyncFunction() { const value = await getRectangleArea(2);}You can also add a try…catch statement to catch errors. Writing this code already feels very similar to writing synchronous code:
async function calcRectangleArea(side) { const rectangleArea = await new Promise((resolve, reject) => { if (typeof side !== 'number') { reject(new TypeError('Please enter a number')); return; } if (side <= 0) { reject(new Error('Please enter a positive number')); return; } setTimeout(() => resolve(side ** 2), 5000); }); console.log(rectangleArea);}
calcRectangleArea(4);Which Approach Should You Use for Asynchronous Code?
It depends on your team and personal preferences; there is no single right or wrong answer. Personally, if there are no constraints (version compatibility or legacy code maintenance), I use Promise + Async / Await. This keeps the syntax concise and makes usage more intuitive and consistent. Ideally, though, you should understand asynchronous programming concepts before using it.
Can You Mix Callbacks, Promise.then(), and Async / Await?
Yes, but it is best not to. Stick to a consistent approach to avoid unnecessary confusion.
Summary
This article explored three approaches to asynchronous JavaScript in sequence: callbacks > Promises and their methods > Async / Await. Depending on what further instruction is needed, I may expand on these topics in the next article 🙂.
References
- Introducing Asynchronous JavaScript
- Why Do We Need Javascript Promises? Inversion of Control | Asynchronous Javascript | Project Twine
- JavaScript Promises: An Introduction