JavaScript 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);
    }
}

Key Takeaways

  • Promises Async Await is an important topic to understand.
  • Start with small examples and practice one step at a time.
  • Use the idea in simple projects so it becomes easier to remember.