Async/Await: Modern Concurrency in JavaScript

Daniel Leitch
Nerd For Tech
Published in
2 min readJan 31, 2021

--

Traditional CPUs process tasks in a synchronous order one operation after another, this was enhanced by multi-threaded CPUs, most PCs today have multiple cored CPUs. The exception to this is Quantum computing but this isn’t in the scope of this post and as of now is not working.

Multi-threaded CPUs enable the CPU to handle multiple problems at once increasing the performance of the PC.

Due to this ‘code’ is synchronous by nature as it is run by the CPU, in JavaScript you give an instruction, that instruction goes to the ‘Call Stack’. The Call stack is the queue of instructions that are waiting to be executed, all the requests line up in the order that they were called.

For instance.

CODE
console.log("Task1");
console.log("Task2");
console.log("Task3");
RESULT
Task1
Task2
Task3

pay attention to the order of execution.

The problem is what happens if something takes a long time to complete?

Let us say you are querying a busy database and the response is taking a while to come back? This would be a disaster as it would hold up the queue until it had finished executing.

This problem was address with Asynchronous functions

Asynchronous allows us to move aside an instruction until the call stack is clear then it will bring it back and re-queue it.

See Below

CODE
console.log(“Task1”);
setTimeout(function(){ console.log(“Task2”); }, 3000);
console.log(“Task3”);
RESULT
Task1
Task3
Task2

So you can see here that we ran the same code as earlier except that we gave “Task 2” an asynchronous function which in this instance is ‘setTimeout’ when the interpreter saw this it placed it aside ( It placed it in the Webapis). Then moved on with the next instruction and call “Task 2” back once it had finished everything else.

They are many kinds of async function available many of which you may have already used. The ‘fetch’ method for instance.

fetch(file)
.then(x => x.text())
.then(y => myDisplay(y));

Since Fetch is based on async and await, the example above might be easier to understand like this:

async function getText(file) {
let x = await fetch(file);
let y = await x.text();
myDisplay(y);
}

The Event Loop

The best way to fully grasp the power of async you need to have a good grasp of how the JavaScript event loop works, this video for me was mega important and changed the way I approached coding altogether.

The next step in understanding async is by playing with it, testing different things. Here is a sandbox that allows you to do just that. Play around with various scenarios (don’t forget to open the console when playing around to see the outputs.)

Source

Resources:

W3School

--

--

Daniel Leitch
Nerd For Tech

I'm a Front-end Developer 🚀 and Linux Enthusiast