How to Create Promise in JavaScript: Simple Guide
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.
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.
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); });
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.
/* 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.