Back to the Basics: Asynchronous JS

Date Created
Sep 3, 2022 03:14 PM
Date Published
Sep 3, 2022
Back to the Basics is a series I’m writing in an effort to revisit fundamentals. Think of it as CS-101 broken up into digestible parts - written primarily for my own benefit 😀
The concept of asynchronous programming is everywhere in JavaScript (and many other languages). When asked about async - at times I have found myself tripping over my own words. I’ve seen it, I’ve used it, I’ve written it - but why? Why is the syntax written the way it is? What was I actually writing when I built async/await functions?
I think it comes down to three primary points:
  1. Why is it important? When should I use it?
  1. How do I use it?
  1. Where do I go next?

Why is it important? When should I use it?

To start - it might be helpful to define what synchronous code is. Synchronous code is code that is evaluated line-by-line in a linear fashion. For the most basic programs - linear evaluation is natural.
Take the following, for example:
function addTwo(num) { return num + 2; } const someNum = 1; const result = addTwo(someNum); console.log(result); // 3
Now, what happens when we add a long-running function to the mix?
function takeXSeconds(sec) { setTimeout(function () { console.log("resolved"); }, 1000 * sec); } takeXSeconds(2); function addTwo(num) { return num + 2; } const someNum = 1; addTwo(someNum);
In this example of synchronous JavaScript - takeXSeconds(sec) delays the execution of the entire program/file. In other words, addTwo() isn’t evaluated until takeXSeconds(2) completes.
Now, what happens when you add async/await to the same program (with Promises):
// Potentially long-running function function takeXSeconds(sec) { return new Promise(resolve => { setTimeout(() => { resolve('resolved'); }, 1000 * sec); }); } // Call the long-running function with async/await async function asyncCall() { console.log("Calling:"); const result = await takeXSeconds(20); console.log(result); } asyncCall(); // The rest of the code is evaluated while the async function is running. function addTwo(num) { return num + 2; } const someNum = 1; console.log(addTwo(someNum));
The same function, takeXseconds(sec), written and evaluated asynchronously.

Wait… what are promises?

Promises are objects returned by async functions, representing the current state of the operation. The promise object provides methods/handlers to handle the success/failure of the function.

Combining Multiple Promises

The promise returned by Promise.all() is:


Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.