</>
CompilerOnline
Open Interactive Editor

JS Promises & Async Programming

Asynchronous JavaScript

A Promise is an object representing the eventual completion or failure of an asynchronous operation. Before promises, asynchronous execution was handled with callbacks, which frequently resulted in deeply nested, unreadable code known as "callback hell".

Promise States:

  • Pending: Initial state, neither fulfilled nor rejected.
  • Fulfilled: The operation completed successfully.
  • Rejected: The operation failed.

Promises support chaining using the .then() method for successes, .catch() for errors, and .finally() for cleanups that must run regardless of the promise outcome.

With the advent of ES8, async and await keywords were introduced to write asynchronous logic in a linear, synchronous-looking style, which makes error handling using standard try-catch blocks straightforward.

Error Handling in Async/Await

When using async/await, you handle potential errors or rejections by placing asynchronous calls inside standard try...catch blocks, mimicking synchronous error handling structures.

javascript
async function fetchUser() {
    try {
        console.log("Fetching...");
        throw new Error("API Offline");
    } catch(err) {
        console.log("Caught Error:", err.message);
    }
}
fetchUser();
javascript
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

async function runAsyncTask() {
    console.log("Task Started...");
    await delay(1000);
    console.log("Task Completed after 1 second!");
}

runAsyncTask();