0
0
JavascriptHow-ToBeginner · 3 min read

How to Create Promise in JavaScript: Simple Guide

To create a Promise in JavaScript, use the new Promise() constructor with a function that takes resolve and reject callbacks. Inside this function, perform your asynchronous task and call resolve(value) when successful or reject(error) if it fails.
📐

Syntax

The basic syntax to create a Promise uses the new Promise() constructor. It takes one function called the executor. This executor function has two parameters: resolve and reject. You call resolve when the task finishes successfully, and reject if there is an error.

javascript
const myPromise = new Promise((resolve, reject) => {
  // asynchronous task here
  if (/* success condition */) {
    resolve('Success value');
  } else {
    reject('Error reason');
  }
});
💻

Example

This example creates a Promise that waits 1 second and then resolves with a message. It shows how to use then to get the result and catch to handle errors.

javascript
const waitOneSecond = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Done waiting 1 second');
  }, 1000);
});

waitOneSecond
  .then(message => {
    console.log(message);
  })
  .catch(error => {
    console.error('Error:', error);
  });
Output
Done waiting 1 second
⚠️

Common Pitfalls

One common mistake is forgetting to call resolve or reject, which leaves the Promise pending forever. Another is calling both resolve and reject — only the first call counts. Also, avoid putting synchronous code that throws errors outside the Promise executor, as it won't be caught by reject.

javascript
/* Wrong: Missing resolve or reject */
const badPromise = new Promise((resolve, reject) => {
  // forgot to call resolve or reject
});

/* Right: Always call resolve or reject */
const goodPromise = new Promise((resolve, reject) => {
  if (true) {
    resolve('All good');
  } else {
    reject('Something went wrong');
  }
});
📊

Quick Reference

Remember these points when creating Promises:

  • Use new Promise((resolve, reject) => { ... }) to create.
  • Call resolve(value) on success.
  • Call reject(error) on failure.
  • Use .then() to handle success and .catch() for errors.
  • Promises run immediately when created.

Key Takeaways

Create a Promise with new Promise(executor) where executor has resolve and reject functions.
Call resolve(value) to mark success and reject(error) to mark failure inside the executor.
Always call either resolve or reject to avoid a Promise that never finishes.
Use then() to handle resolved values and catch() to handle errors.
Promises start running immediately when created, so put async code inside the executor.