Creating Promises

Med

A Promise is an object representing the eventual completion or failure of an asynchronous operation. Promises are created using the new Promise(executor) constructor, which takes a function with resolve and reject parameters. Understanding Promise creation is fundamental to working with modern asynchronous JavaScript.

Interactive Visualization

Executor Function
Not Started
resolve()
reject()
CodeCreation
1const p = new Promise((resolve, reject) => {
2 console.log("Executor runs!");
3 resolve("Done");
4});
5
6console.log("After Promise");
Promise State
p
PENDING
Console Output
-
Promise constructor is called - executor function will run immediately
1 / 4
Key Insight: The executor function runs SYNCHRONOUSLY when you create a Promise. Code after new Promise() runs AFTER the executor completes.

Key Points

  • new Promise(executor) creates a Promise object
  • Executor receives resolve and reject functions
  • Call resolve(value) to fulfill the Promise
  • Call reject(error) to reject the Promise
  • Promise starts in "pending" state, settles to "fulfilled" or "rejected"
  • Once settled, a Promise cannot change state

Code Examples

Basic Promise Creation

const promise = new Promise((resolve, reject) => {
  // Async operation
  setTimeout(() => {
    resolve("Success!"); // Promise is fulfilled
  }, 1000);
});

// The promise starts pending, then becomes fulfilled
console.log(promise); // Promise {<pending>}

promise.then(result => {
  console.log(result); // "Success!" (after 1 second)
});

Create a Promise with new Promise(). Call resolve() when the operation succeeds.

Promise Rejection

const promise = new Promise((resolve, reject) => {
  const success = false;
  
  if (success) {
    resolve("Operation succeeded");
  } else {
    reject(new Error("Operation failed")); // Promise is rejected
  }
});

promise
  .then(result => console.log(result))
  .catch(error => console.log(error.message)); // "Operation failed"

Call reject() with an Error object when the operation fails.

Converting Callback to Promise

// Original callback-based function
function fetchData(callback) {
  setTimeout(() => {
    callback(null, "Data"); // (error, result)
  }, 1000);
}

// Converted to Promise
function fetchDataPromise() {
  return new Promise((resolve, reject) => {
    fetchData((error, result) => {
      if (error) {
        reject(error);
      } else {
        resolve(result);
      }
    });
  });
}

// Usage
fetchDataPromise()
  .then(data => console.log(data))
  .catch(err => console.error(err));

Wrap callback-based APIs in Promises for cleaner async code.

Promise State Transitions

console.log("Creating promise...");

const promise = new Promise((resolve, reject) => {
  console.log("Executor runs immediately!"); // Synchronous
  
  setTimeout(() => {
    resolve("Done");
    console.log("Already resolved, this does nothing:");
    resolve("Ignored"); // Second resolve is ignored!
  }, 1000);
});

console.log("Promise created:", promise);

// Output:
// "Creating promise..."
// "Executor runs immediately!"
// "Promise created:" Promise {<pending>}
// ...1 second...
// "Done"
// "Already resolved, this does nothing:"

The executor runs synchronously. Once resolved/rejected, a Promise cannot change state.

Common Mistakes

  • Forgetting to return the Promise from a function
  • Calling both resolve and reject (only first one matters)
  • Not wrapping errors in reject (should use Error objects)
  • Thinking the executor runs asynchronously (it runs synchronously)

Interview Tips

  • Know the Promise constructor syntax
  • Understand that executor runs synchronously
  • Know that Promises are immutable once settled
  • Be able to convert a callback API to Promises