Promises

Write cleaner asynchronous code with promises and async functions.

Interactive applications often perform tasks that take time, such as loading data, uploading files, or processing payments. These tasks happen asynchronously, meaning JavaScript does not wait for them to finish before continuing with other code.

Promises and Async/Await make asynchronous code easier to read, write, and maintain.

What Is a Promise?

A Promise is an object that represents the result of an asynchronous operation.

  • Pending: the task is still running.
  • Fulfilled: the task completed successfully.
  • Rejected: the task failed.

Creating a Promise

javascript
const myPromise = new Promise((resolve, reject) => {
    let success = true;

    if (success) {
        resolve("Data loaded successfully");
    } else {
        reject("Something went wrong");
    }
});

Handling Promises

javascript
myPromise
    .then(result => {
        console.log(result);
    })
    .catch(error => {
        console.log(error);
    });

Output:

javascript
Data loaded successfully

Promise Chaining

javascript
Promise.resolve(5)
    .then(num => num * 2)
    .then(num => num + 10)
    .then(result => console.log(result));

Output:

javascript
20

What Is Async/Await?

Async/Await provides a cleaner way to work with Promises.

Using async

javascript
async function getData() {
    return "Data received";
}

An async function automatically returns a Promise.

Using await

javascript
function fetchData() {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve("Data loaded");
        }, 2000);
    });
}

async function displayData() {
    const result = await fetchData();
    console.log(result);
}

displayData();

Output:

javascript
Data loaded

Error Handling with try...catch

javascript
async function loadData() {
    try {
        const result = await fetchData();
        console.log(result);
    } catch (error) {
        console.log(error);
    }
}

Real-World Example

In a weather application, Promises and Async/Await allow JavaScript to wait for server data without freezing the page.

Summary

Promises represent future results and allow developers to manage success and failure using then() and catch(). Async/Await builds on Promises and provides a cleaner, more readable way to write asynchronous code.

Let's learn with DevBrainBox AI