DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,155 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Karen Molina
Karen Molina

Posted on

Asynchronous JavaScript: callbacks, promises and async/await.

Hi!

First JavaScript is a single-threaded programming language, which means only one thing can happen at a time. That happen, because the JavaScript engine can only process one statement at a time. So, the asynchronous is the action that do not happen at a time. And, Why is important understand the asynchronous in JS?. Always we work with data, sometimes we have to work with some APIs and depending the situation the server take some time to process the request at a time block the tread making the web unresponsive. That's where asynchronous comes into play.

JavaScript has three ways to handle the asynchronous: callbacks, promises and async/await.

Callbacks

A callback is a function passed into another functions as an argument.

function myName(name) {
  return name
}

function hello(callback) {
  console.log("Hello" + " " + callback)
}

hello(myName("Karen")) // Hello Karen
Enter fullscreen mode Exit fullscreen mode

In this case, we have two functions, in the first, we need to get a value: name. So, we get it within a function. In the second function, we use the value that we returned at the first function and we use it in the second. So, to make it successful, we're going to passe the myName functions as a parameter inside the hello function.

Promises

A promise is a special object in JavaScript, 'cause that links the producer code and consuming code. When we talk about producer code, we must through something that takes time to be processed. And the consuming code as something to provide us a result.

A promise has two properties: the state and the result.
The state can be: pending, fulfilled and rejected.
The result can be: undefined, a result value or an error object.

Now the syntax for a promise is next:

let thePromise = new Promise(function(resolve, reject) {
  resolve("done");
  reject(new Error("…")); 
});
Enter fullscreen mode Exit fullscreen mode

Inside a promise, we have two arguments: resolve and reject. Both arguments are callbacks provided by JS. The resolve callback is being executed if the job is finished successfully. Meanwhile, the reject is be executed if an error has occurred.

Async/Await

Make the promises easier to write within two keywords:
1.- Async: Makes a functions return a promise.
2.- Await: Makes a functions wait for a promise.

const myName = (name) => name

const hello = async () => {
  const result = await myName("Karen")
  console.log(`Hello ${result} `) // Hello Karen
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.