Skip to main content

Promises and Async/Await

Introduction

JavaScript is a single-threaded language, meaning it can only handle one operation at a time. With the rise of modern web technologies and complex operations, JavaScript needed a way to handle multiple operations simultaneously. This is where Promises and Async/Await come into play. They are used to handle asynchronous operations in JavaScript, allowing you to write non-blocking code.

Promises

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

Creating a Promise

A Promise is created using the Promise constructor. Here's an example:

let promise = new Promise(function(resolve, reject) {
// some code

if (/* everything turned out fine */) {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});

In this example, resolve and reject are callbacks provided by JavaScript itself. You call resolve when the asynchronous operation completes successfully and returns the results. You call reject when the operation fails and returns an error.

Using a Promise

Once a Promise is created, it can be used. Here's how you can attach callbacks to a Promise:

promise.then(function(result) {
console.log(result); // "Stuff worked!"
}, function(err) {
console.log(err); // Error: "It broke"
});

You can also chain multiple .then() methods, allowing you to perform multiple asynchronous operations in sequence.

Async/Await

While Promises provide a solution to callback hell, they can still become complex as they're chained over time. This is where Async/Await shines – it makes your asynchronous code look and behave like synchronous code.

Async Functions

An async function is a function declared with the async keyword. This function always returns a promise.

async function helloWorld() {
return "Hello, World!";
}

helloWorld().then(alert); // Hello, World!

Await

The await operator is used to wait for a Promise. It can only be used inside an async function. Here's an example:

async function helloWorld() {
let response = await fetch('https://api.github.com/users/github');
let user = await response.json();
return user.name;
}

helloWorld().then(alert); // GitHub

In this example, fetch returns a Promise. await is used to wait for the Promise to resolve or reject, and only then does it assign the result to the response variable.

Conclusion

Promises and Async/Await are powerful tools in JavaScript that help you write clean, readable, and maintainable asynchronous code. They help you avoid callback hell and make your asynchronous code look and behave like synchronous code. While they might seem complex at first, with time and practice, they'll become an invaluable part of your JavaScript toolkit.