Back to Lessons

JavaScript Promises and Async

April 5, 2026

Promises and Asynchronous JS

Handle asynchronous operations without callback hell.

Promise Example

function fetchData() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (Math.random() > 0.5) {
                resolve("Data received");
            } else {
                reject("Error occurred");
            }
        }, 1000);
    });
}

fetchData()
    .then(result => console.log(result))
    .catch(error => console.error(error));

Key Points

  • Promise states: pending, fulfilled, rejected.
  • .then(), .catch(), .finally() chaining.
  • Promise.all(), Promise.race() for multiple promises.
  • Replaces callbacks for cleaner async code.