Promises in JavaScript

Understanding Promises is crucial for writing asynchronous JavaScript code effectively.

What are Promises?

A Promise represents the eventual result of an asynchronous operation. It either succeeds with a resolved value or fails with a rejection reason. Promises provide a cleaner and more manageable way to handle asynchronous code compared to callbacks.

Think of a promise as a container holding a value that might not be available yet, but will be resolved when the operation completes.

Promise States

A promise has three possible states:

Creating Promises

There are several ways to create promises:


Promise.resolve(10) // Immediately resolved promise
Promise.reject(new Error('Something went wrong')) // Immediately rejected promise
Promise.resolve(setTimeout(() => { console.log('Hello from Promise!'); }, 1000))
// You can also use the 'new' keyword, but it's less common now:
// const myPromise = new Promise((resolve, reject) => { ... });
            

Common Promise Methods