Skip to main content

What is a Promise?

Definition

Promise is a special object in JavaScript that represents the result of an asynchronous operation, which may complete later - successfully or with an error.

In simpler terms, a Promise is a "promise" to deliver a result in the future. There is no answer right now, but there will be one once the operation finishes.


Three states of a promise

StateDescriptionExample
pending"waiting" - the operation has not finished yeta request in progress
fulfilled"completed successfully" - there is a resultdata received
rejected"rejected" - an error occurredthe server returned 404

Example 1 - Creating a promise manually

javascript
const promise = new Promise((resolve, reject) => { const success = Math.random() > 0.5; if (success) { resolve('Success!'); } else { reject('Error!'); } });
  • resolve(value) moves the promise to the fulfilled state;
  • reject(error) moves it to the rejected state.

Handling the result

javascript
promise .then((result) => { console.log('Result:', result); }) .catch((error) => { console.error('Error:', error); }) .finally(() => { console.log('Always runs'); });

What each method does:

MethodWhen it is calledWhat it returns
.then()on success (resolve)a new Promise
.catch()on an error (reject)a new Promise
.finally()in either case (success or error)a new Promise

Example 2 - Asynchronous code with Promise

javascript
function fetchData() { return new Promise((resolve) => { setTimeout(() => { resolve('Data received!'); }, 2000); }); } fetchData().then((data) => console.log(data));

fetchData() returns a Promise -> after 2 seconds it resolves, and then() receives the result.


Example 3 - Handling errors

javascript
function fetchUser() { return new Promise((_, reject) => { setTimeout(() => reject('User not found'), 1000); }); } fetchUser() .then(user => console.log(user)) .catch(err => console.error(err));

Output:

javascript
User not found

Promise chaining

Every .then() returns a new Promise, so you can build chains of asynchronous actions:

javascript
getUser() .then(user => getPosts(user.id)) .then(posts => getComments(posts[0].id)) .then(comments => console.log(comments)) .catch(err => console.error('Error:', err));

Advantage: No nesting -> reads top to bottom (unlike callback hell).


Shorthand form - Promise.resolve() and Promise.reject()

javascript
Promise.resolve('OK').then(console.log); // "OK" Promise.reject('Error').catch(console.error); // "Error"

Parallel promises

Promise.all() - waits until all of them complete

javascript
Promise.all([ fetch('/user'), fetch('/posts'), ]).then(([userRes, postRes]) => { console.log('Both responses received'); });

If even one promise ends with an error, the whole all() becomes rejected.


Promise.allSettled() - waits for all of them, regardless of errors

javascript
Promise.allSettled([ fetch('/user'), fetch('/wrong-url'), ]).then(console.log);

Result:

javascript
[ { status: "fulfilled", value: Response }, { status: "rejected", reason: TypeError } ]

Promise.race() - returns the first one to complete

javascript
Promise.race([ fetch('/slow'), fetch('/fast'), ]).then(console.log);

Promises and async/await

Promises are the foundation that async/await syntax is built on:

javascript
async function main() { try { const user = await getUser(); const posts = await getPosts(user.id); console.log(posts); } catch (err) { console.error(err); } }

Here await simply waits for a Promise, but makes the code linear and clear.


A simple analogy

A promise is like a pizza delivery.

  • You place an order -> the promise is created (pending)
  • The courier is bringing the order -> the operation is in progress
  • The courier arrives -> the promise resolves
  • The courier gets lost -> the promise rejects

You can "subscribe" to the result (then) and "handle" errors (catch).


SUMMARY

TermDescription
PromiseAn object representing the future result of an asynchronous operation
Statespending -> fulfilled or rejected
Methods.then(), .catch(), .finally()
Main advantageSimplifies working with asynchrony, removes callback hell
Modern syntaxasync/await is built on Promise

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.