logo
Published on

Exploring Promises and Async/Await in JavaScript

Table of Contents

Introduction

JavaScript is an asynchronous language, which means that it can handle multiple tasks simultaneously without blocking the main thread. This allows for more efficient and responsive web applications. However, asynchronous programming can also make code harder to read and debug. Promises and async/await are two features of JavaScript that help manage asynchronous code.

Promises

Promises are objects that represent a value that may not be available yet but will be resolved in the future.

A Promise has three states: pending, fulfilled, and rejected. When a Promise is pending, it means that it is waiting for the value to be resolved. When a Promise is fulfilled, it means that the value is available. When a Promise is rejected, it means that an error has occurred.

Promises have two main methods: then and catch. The then method is used to handle a fulfilled Promise, while the catch method is used to handle a rejected Promise.

Here's an example of how to use a Promise:

const myPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
        const randomNum = Math.random()
        if (randomNum > 0.5) {
            resolve(randomNum)
        } else {
            reject('Value is less than 0.5')
        }
    }, 1000)
})

myPromise
    .then((value) => {
        console.log(value)
    })
    .catch((error) => {
        console.log(error)
    })

In this example, a Promise is created using the new Promise syntax. The setTimeout function is used to simulate an asynchronous operation that resolves to a random number. If the random number is greater than 0.5, the Promise is resolved with the random number. If the random number is less than or equal to 0.5, the Promise is rejected with an error message.

The then method is used to handle the resolved Promise by logging the value to the console. The catch method is used to handle the rejected Promise by logging the error message to the console.

Async/Await

Async/await is a newer feature of JavaScript that allows for even more concise and readable asynchronous code. Async/await is built on top of Promises, so it's important to understand Promises before using async/await.

Async/await is essentially syntactic sugar for Promises. Async functions always return a Promise, and the await keyword is used to wait for a Promise to resolve.

Here's an example of how to use async/await:

function wait(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms))
}

async function myAsyncFunction() {
    console.log('Starting...')
    await wait(1000)
    console.log('Finished!')
}

myAsyncFunction()

In this example, an async function is created using the async keyword. The wait function returns a Promise that resolves after a certain number of milliseconds. The await keyword is used to wait for the wait function to resolve before moving on to the next line of code.

When myAsyncFunction is called, it logs "Starting..." to the console, waits for 1000 milliseconds using the wait function, and then logs "Finished!" to the console.

Summary

Promises and async/await are two powerful features of JavaScript that make asynchronous programming more manageable. Promises allow for easy handling of asynchronous operations by providing a way to handle asynchronous values when they become available. Async/await makes asynchronous programming even easier by providing a more concise and readable syntax