JavaScript Interview Question #78

What is a Promise in JavaScript?

Promises, Async/Await, Fetch & Modern JavaScript Mid-Level Intermediate

Quick Interview Answer

A Promise is an object representing the eventual completion or failure of an asynchronous operation. It allows code to register handlers for a future result instead of nesting callbacks.

Detailed Explanation

A Promise is an object representing the eventual completion or failure of an asynchronous operation. It allows code to register handlers for a future result instead of nesting callbacks.

A Promise is created in the pending state and later becomes fulfilled with a value or rejected with a reason. Once settled, its state cannot change again.

Code Example

const promise = new Promise((resolve, reject) => {
    const success = true;

    if (success) {
        resolve("Operation completed");
    } else {
        reject(new Error("Operation failed"));
    }
});

promise.then(value => console.log(value));