Asynchronous JavaScript - what is it? (Promises, callbacks, async/await)

Tags: javascript, beginners, 100daysofcode, codenewbie
Published: 2020-09-14 07:37:39

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/etb07y55qkybdwff33lk.jpeg)
_Article originally published on [Tinloof](https://tinloof.com/blog/asynchronous-javascript-what-is-it/)_

JavaScript code is executed synchronously. In other words, from top to bottom and one line at a time.

```js
function getText() {
  return "Hi 👋, I'm Tinloof";
}

let text = getText();
console.log(text);

// Output:
// Hi 👋, I'm Tinloof
```

First, the code will execute the function and know what to return when `getText()` is called.

Then it assigns the `getText()` function to the variable `text`.

Finally, it logs the variable text to the console, and the output is "Hi 👋 , I'm Tinloof".

So far, this works great and we're facing no obstacle.

Now, imagine we have to make a network request to get the text "Hi 👋 , I'm Tinloof" and the user doesn't have a fast Internet connection.


```js
// Assume getTextFromServer is making a network request to get data

let text = getTextFromServer();

// 🕰 Wait until we receive the text from the server
// 🍦 Meanwhile the page is frozen and the user can't interact with it

console.log(text);

// Output:
// Hi 👋, I'm Tinloof

```

The code works, but while we wait for the text from the server, our page freezes.

One appraoch to solve this problem is called "callbacks".

# Callback functions

```js
getTextFromServer((error, text) => {
  if (error) {
    console.log("Error getting the text:", error);
  } else {
    console.log(text);
  }
});

// Output (if we successfully get the text from the server)
// Hi 👋 , I'm Tinloof

// Output (if we are not successfully getting the text from the server)
// Error getting the text: some error from the server.
```

Instead of waiting for `getTextFromServer()` to finish, we let it run in the background and pass to it a function, called "callback function" or "callback", to handle the result of the call once it's done.

To handle the scenario where the request fails or the one where it succeeds, our callback function takes 2 parameters:
1. An error, which is empty if the request is successful
2. A result (in our case it's the text "Hi 👋 , I'm Tinloof")


> **Notice:** If you're not familiar with arrow functions, here's a [link to the MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions).

## We just wrote our first asynchronous code!

Guess what? We just learned one approach of writing asynchronous code in JavaScript. 

In the example above, while our code is looking to get the text from the server, the rest of our code would still run.

Another approach to asynchronous code is called _Promises_. 

# **Promise**

```js
let promise = getTextFromServer();

promise
  .then((text) => {
    console.log(text);
  })
  .catch((error) => {
    console.log("Error getting the text:", error);
  });

// Output (if we successfully get the text from the server)
// Hi 👋 , I'm Tinloof

// Output (if we are not successfully getting the text from the server)
// Error getting the text: some error from the server.
```

Instead of accepting a callback, `getTextFromServer()` returns a Promise object. 

A Promise is an object that gives us the result of the success of an asynchronous operation or the result of its failure (it either resolves or rejects). 

It does that by providing a `then()` function to handle success and `catch()` to handle errors.

JavaScript has a syntatic sugar (jargon for "more beautiful syntax") for Promises, let's check it out.

# async/await

```js
try {
  let text = await getTextFromServer();
  console.log(text);
} catch (error) {
  console.log("Error getting the text:", error);
}

// Output (if we successfully get the text from the server)
// Hi 👋 , I'm Tinloof

// Output (if we are not successfully getting the text from the server)
// Error getting the text: some error from the server.
```

Instead of using the Promise syntax, which can be confusing at times, we simply await `getTextFromServer()` using the `await` keyword.

To handle the error and success scenarios, we surround our code in a `try/catch` block. 

If the request is successful, the `try` block will be executetd to its end and the text will be printed.

If the request fails, we'll jump directly from the await line to the `catch` block and output the error.

## Using "await" in a function

If we want to use the `await` syntax in a function, the function has to be declared with the `async` keyword.

```js
async function getText() {
  try {
    let text = await getTextFromServer();
    console.log(text);
  } catch (error) {
    console.log("Error getting the text:", error);
  }
}

console.log(getText);

// Output (if we successfully get the text from the server)
// Hi 👋 , I'm Tinloof

// Output (if we are not successfully getting the text from the server)
// Error getting the text: some error from the server.
```

# Conclusion

We now know what Asynchronous JavaScript is, and learned how to write it with 3 approaches:

- Callback functions
- Promises
- `async...await` (which is just a prettier syntax of Promises)

Believe it or not, if you made it so far while understanding everything, you can build most features that require asynchronous code.

Though, we strongly advise you to dig deeper in the topic. Here are a few resources:

- [What the heck is the event loop anyway?](https://www.youtube.com/watch?v=8aGhZQkoFbQ) by [Philip Roberts](https://twitter.com/philip_roberts)

- [Asynchronous programming](https://exploringjs.com/es6/ch_async.html) by [Axel Rauschmayer](https://twitter.com/rauschma)

- [Rethinking Asynchronous JavaScript](https://frontendmasters.com/courses/rethinking-async-js/) by [Kyle Simpson](https://twitter.com/getify) on Frontend Masters. You can also read the book YDKJS for free [here](https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/async%20%26%20performance/ch1.md)

- [Async + Await in JavaScript](https://www.youtube.com/watch?v=DwQJ_NPQWWo) by [Wes Bos](https://twitter.com/wesbos)

- [Async-Await cheatsheet from CodeCademy](https://www.codecademy.com/learn/introduction-to-javascript/modules/asynch-js/cheatsheet)