Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is asynchronous in JavaScript

Understanding Asynchronousity

In the realm of programming, things often happen one after the other - we call this synchronicity. However, JavaScript, our beloved, web-based language, has a unique trait - it can perform tasks 'asynchronously'. If you're scratching your head, it's alright. The term 'asynchronous' might sound a bit intimidating, but it's a simple concept.

Imagine you're cooking dinner. You've got your pasta boiling on one stove top, sauce simmering on another, and garlic bread toasting in the oven. You don't wait for the pasta to finish boiling before you start the sauce, or the sauce to finish before you put the bread in the oven. You do all these tasks at once, moving back and forth between them as needed. That's what we mean by 'asynchronous' - things don't have to wait in a line to get done; they can happen simultaneously.

JavaScript's Asynchronous Nature

JavaScript is a single-threaded language. Think of it as being a chef with only one hand. It can only do one thing at a time. But it cheats a little. Using something called the 'event loop', it can handle multiple tasks at the same time, just like our chef juggling pasta, sauce, and bread.

Here's a code example:

console.log('I am first');
setTimeout(function() {
 console.log('I am second');
}, 1000);
console.log('I am third');

If JavaScript was strictly synchronous, you would expect it to print 'I am first', wait for one second, print 'I am second', and then print 'I am third'. But if you run this code, you'll see that 'I am third' gets printed before 'I am second'. That's JavaScript's asynchronous nature at play.

Making Sense of setTimeout()

You might be wondering about the magic behind the setTimeout() function. It's a built-in JavaScript function that allows us to delay the execution of a piece of code.

We tell JavaScript, "Hey, I want you to do this task, but not right now. Do it after a certain amount of time has passed." In the example above, we told JavaScript to wait for one second (1000 milliseconds) before printing 'I am second'.

But here's the tricky part. When JavaScript sees the setTimeout() function, it doesn't sit around doing nothing for that one second. It moves on to the next line of code, which is why 'I am third' gets printed before 'I am second'.

Promises and Async/Await

JavaScript has a couple more tricks up its sleeve when it comes to handling asynchronous tasks - Promises and the async/await syntax.

A Promise in JavaScript is an object representing the eventual completion or failure of an asynchronous operation. It's like when you order a pizza. The pizzeria promises to deliver your pizza in the future, and until then, you can go about doing other tasks.

Here's how a Promise looks in JavaScript:

let pizzaPromise = new Promise((resolve, reject) => {
  let pizzaArrived = true;
  if (pizzaArrived) {
    resolve('Pizza is here!');
  } else {
    reject('No pizza. Sad!');
  }
});

pizzaPromise.then(message => {
  console.log(message);
}).catch(error => {
  console.log(error);
});

The async/await syntax is another way to handle Promises. It makes your asynchronous code look more like traditional synchronous code, which can be easier to understand.

async function getPizza() {
  let pizzaPromise = new Promise((resolve, reject) => {
    let pizzaArrived = true;
    if (pizzaArrived) {
      resolve('Pizza is here!');
    } else {
      reject('No pizza. Sad!');
    }
  });

  let result = await pizzaPromise;
  console.log(result);
}

getPizza();

Concluding Thoughts

As we pull down the shutters of our digital kitchen, let's take a moment to appreciate JavaScript's asynchronousity. It's like a masterful chef, juggling multiple tasks, and always keeping us on our toes. Understanding asynchronous JavaScript is like learning to dance to the rhythm of the kitchen - it might seem chaotic at first, but once you get the hang of it, you'll be creating culinary (or in our case, coding) masterpieces in no time.