Suggest an editImprove this articleRefine the answer for “What is a Promise?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)A **`Promise`** is a special object in JavaScript that **represents the result of an asynchronous operation**, which **may complete later** - successfully or with an error. **Key point:** a promise moves through the states `pending` -> `fulfilled` or `rejected`, and `async/await` syntax is built on top of promises.Shown above the full answer for quick recall.Answer (EN)Image## 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 | State | Description | Example | |---|---|---| | **pending** | "waiting" - the operation has not finished yet | a request in progress | | **fulfilled** | "completed successfully" - there is a result | data received | | **rejected** | "rejected" - an error occurred | the 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:** | Method | When it is called | What 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 | Term | Description | |---|---| | **Promise** | An object representing the future result of an asynchronous operation | | **States** | `pending` -> `fulfilled` or `rejected` | | **Methods** | `.then()`, `.catch()`, `.finally()` | | **Main advantage** | Simplifies working with asynchrony, removes callback hell | | **Modern syntax** | `async/await` is built on Promise |For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.