> For the complete documentation index, see [llms.txt](https://mihai-gheorghe.gitbook.io/tic/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mihai-gheorghe.gitbook.io/tic/advanced-javascript/asynchronous-javascript.md). Agents can also search and read this documentation through its [MCP server](https://mihai-gheorghe.gitbook.io/tic/~gitbook/mcp).

# Asynchronous JavaScript

## Synchronous execution

Basically, referring to a programming language, **Synchronous** means executing tasks **one at a time** in the order described by the source code. This means we cannot execute a certain operation until the previous one has finished.

However, in modern web applications, this kind of behavior would have a great impact on usability given the fact that certain tasks (such as communicating via network) might take an unreasonable time to complete, blocking the main thread of execution.

{% tabs %}
{% tab title="Synchronous  execution" %}

```javascript
let i = 0
function expensiveOperation() {
    //some code that needs a long time to execute
}

expensiveOperation() //taking 5 seconds
console.log("It's been a while")
```

{% endtab %}
{% endtabs %}

The engine runs on a single thread, with one call stack (see [Engine, Call Stack, Scope and Closures](https://mihai-gheorghe.gitbook.io/tic/advanced-javascript/runtime-engine-callstack.md#execution-context-and-the-call-stack)): while `expensiveOperation()` is on the stack, the page cannot respond to clicks or update what it shows.

## Asynchronous execution

Luckily, JavaScript Runtimes (such as browsers or NodeJS) have important additions to the core JavaScript engine, allowing an Asynchronous behavior.

A **runtime** = engine + Web/Host APIs + queues + event loop. The engine is single-threaded, but the runtime exposes asynchronous primitives (timers, network, DOM events) that schedule work back to JS.

![The JavaScript runtime in the browser: engine, Web APIs, callback queue and event loop](https://1172597814-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MJ6Mj8gFbz9Ji6QL6Zi%2Fuploads%2Fgit-blob-072a6da22fe39da877df3e7eed4d51a9389adc41%2Fjs-runtime.svg?alt=media)

Some features aren't native in JavaScript, but are available through the browser runtime, which exposes them through APIs; timers and network requests run in the background, outside the engine:

1. the console: `console.log()` displays the evaluation between the brackets
2. the HTML DOM: `document.getElementById()` allows us to change what is rendered
3. timers: `setTimeout(expensiveOperation, 3000)` or `setInterval()` start a timer in a background browser process
4. the network: `XMLHttpRequest()` and the more recent `fetch()` issue network requests and retrieve external answers

When a timer expires, the user clicks or an `XMLHttpRequest` response arrives, the runtime places the corresponding callback in the **callback queue**. The **event loop** waits until the call stack is empty and only then moves the next callback from the queue onto the stack. In what order are the numbers below printed?

```javascript
// Inspect order with DevTools
debugger; // step to observe the stack frames

console.log("1");
setTimeout(function () {
  console.log("2");
}, 3000);
console.log("3");
console.log("4");
console.log("5");
setTimeout(function () {
  console.log("6");
}, 0);
console.log("7");
console.log("8");
console.log("9");
```

<details>

<summary>Output</summary>

`1 3 4 5 7 8 9`, then `6`, then `2` after about 3 seconds. Even with a delay of 0 ms, a `setTimeout()` callback waits in the callback queue until the call stack is empty.

</details>

## Callbacks

A callback is a function passed as an argument, to be called later, for example when a timer expires or a response arrives. When each step depends on the previous one, callbacks nest inside each other and the code becomes hard to read and to handle errors in, a situation known as **callback hell**:

```javascript
setTimeout(() => {
  console.log('Step 1');
  setTimeout(() => {
    console.log('Step 2');
    setTimeout(() => {
      console.log('Step 3');
    }, 1000);
  }, 1000);
}, 1000);
```

Promises and async/await, below, express the same sequence as a flat chain.

## Promises

A `Promise` is an object representing the eventual completion or failure of an asynchronous operation. Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function.

A promise is first **pending**, then becomes either **fulfilled**, with a value, or **rejected**, with an error. `.then()` registers a handler for the fulfilled case and `.catch()` one for the rejected case. Each call returns a new promise, which is what allows chaining. When a promise settles, its handlers are queued in the MicroTask queue.

```javascript
new Promise((resolve, reject) => {
    console.log('Initial');
    //issue a network request

    setTimeout(()=> resolve('The response'), 2000);
})
.then((res) => {
    console.log(res)
    //assuming we're creating a new promise that rejects
    throw new Error('Something failed');

    console.log('Do this'); // never runs
})
.catch(() => {
    console.error('Do that');
})
.then(() => {
    console.log('Do this, no matter what happened before');
});
```

Web APIs such as `fetch()` return promises. `fetch()` sends the request through the browser and returns at once; the handlers attached with `.then()` run when the response arrives, after the synchronous code:

{% tabs %}
{% tab title="Asynchronous JavaScript example" %}

```javascript
const printData = data => console.log(data)
const printHello = () => console.log('Hello')
const expensive300msOperation = () => {}

setTimeout(printHello, 0) //printHello is a callback
//being a callback for a browser API, it gets pushed to the callback queue
const futureData = fetch('https://api.tvmaze.com/shows') //it returns a Promise
futureData //let's assume this takes 200ms
    .then(response => response.json()) //this gets pushed to the microtasks queue
    .then(printData) ////this gets pushed to the microtasks queue
    .catch(error => console.log('We encountered the following error: ' + error))

expensive300msOperation() //pushed to the Call Stack
console.log('Print me first!')
// Prints: Print me first!, then Hello, then the data when the response arrives
```

{% endtab %}
{% endtabs %}

## Microtasks and tasks

Promise handlers wait in a separate queue, the **microtask queue**. Microtasks run as soon as the call stack is empty, before the next task from the callback queue (the **task queue**):

| Microtasks (higher priority)                                             | Tasks, also called macrotasks (lower priority)                                                                      |
| ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------- |
| `.then()`, `.catch()` and `.finally()` handlers                          | `setTimeout()` and `setInterval()` callbacks                                                                        |
| the code after `await`                                                   | DOM events: `click`, `input`, `keydown`                                                                             |
| `queueMicrotask(fn)`                                                     | network events, such as `load` for `XMLHttpRequest`                                                                 |
| `MutationObserver` callbacks                                             | messages sent with `postMessage()`                                                                                  |
|                                                                          | the main script itself                                                                                              |
| **In each round:** all of them, including the ones added in the meantime | **In each round:** only one, after the microtask queue is empty                                                     |
| **Starvation:** none, they always run before the next task               | **Starvation:** if every microtask adds a new one, tasks wait indefinitely, and so does rendering: the page freezes |

![Where each operation runs, and one round of the event loop: one task, all the microtasks, then rendering](https://1172597814-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MJ6Mj8gFbz9Ji6QL6Zi%2Fuploads%2Fgit-blob-845c447ae8e1f2bdca56be9511bc8a272f75ea8e%2Fjs-event-loop.svg?alt=media)

In what order are the four messages printed?

```javascript
console.log("Start");

setTimeout(function () {
  console.log("Timeout callback");
}, 0);

Promise.resolve().then(function () {
  console.log("Promise microtask");
});

console.log("End");
```

<details>

<summary>Output</summary>

`Start`, `End`, `Promise microtask`, `Timeout callback`. Promise handlers run before `setTimeout(fn, 0)` callbacks.

</details>

{% hint style="danger" %}
The event loop repeats the same cycle: it runs one task from the callback queue, then empties the microtask queue completely, and only then can the browser render and move on to the next task. A long chain of microtasks therefore delays timers, DOM events and rendering.
{% endhint %}

## Async/await

The `async` keyword can be placed before a function, which will return a promise. The returned values of the function will be wrapped in a resolved promise automatically.

```javascript
async function f() {
  return 1;
}

f().then((res) => console.log(res)); // 1
```

The keyword `await` pauses the async function until the promise settles and then returns its result. Only that function waits: the rest of the program keeps running.

```javascript
async function f() {

  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("done!"), 1000)
  });

  let result = await promise; // wait until the promise resolves (*)

  console.log(result); // "done!"
}

f();
```

It’s a more elegant syntax of getting the promise result than `promise.then`, easier to read and write. Errors from a rejected promise are handled with an ordinary `try`/`catch`:

```javascript
async function loadShows() {
  try {
    const response = await fetch('https://api.tvmaze.com/shows');
    const shows = await response.json();
    console.log(shows.length);
  } catch (error) {
    console.log('We encountered the following error: ' + error);
  }
}
```

## Running several promises

`Promise.all()` waits for all the promises in a list and `Promise.race()` only for the first one to settle; awaiting them one by one runs them in sequence:

```javascript
//multiple async
const promisify = (item, delay) =>
  new Promise((resolve) =>
    setTimeout(() =>
      resolve(item), delay));

const a = () => promisify('a', 100);
const b = () => promisify('b', 5000);
const c = () => promisify('c', 3000);

async function parallel() {
  const promises = [a(), b(), c()];
  const [output1, output2, output3] = await Promise.all(promises);
  return `parallel is done: ${output1} ${output2} ${output3}`
}

async function race() {
  const promises = [a(), b(), c()];
  const output1 = await Promise.race(promises);
  return `race is done: ${output1}`;
}

async function sequence() {
  const output1 = await a();
  const output2 = await b();
  const output3 = await c();
  return `sequence is done ${output1} ${output2} ${output3}`
}

sequence().then(console.log) // after about 8.1 s: one promise after another
parallel().then(console.log) // after about 5 s: all at once, waiting for the slowest
race().then(console.log)     // after about 0.1 s: the first one to settle
```

## Takeaways

* Synchronous code blocks the single thread; timers, network requests and events are handled by the runtime, which queues their callbacks.
* The event loop runs a callback only when the call stack is empty, and empties the microtask queue (promise handlers) before each new task (timers, events).
* Promises and async/await replace nested callbacks with flat code; handle their errors with `.catch()` or with `try`/`catch`.
