Promises & Async/Await
What is a Promise?
Section titled “What is a Promise?”A Promise is an object representing the eventual result (or failure) of an asynchronous operation.
3 States of a Promise
Section titled “3 States of a Promise”- Pending - Waiting for result
- Fulfilled - Succeeded with a value
- Rejected - Failed with an error
Examples
Section titled “Examples”Creating a Promise
Section titled “Creating a Promise”const fetchData = () => { return new Promise((resolve, reject) => { setTimeout(() => { resolve({ id: 1, name: 'Notex' }); }, 1000); });};Async/Await
Section titled “Async/Await”async function getData() { try { const data = await fetchData(); console.log(data); } catch (error) { console.error('Error:', error); }}Promise.all - Run in Parallel
Section titled “Promise.all - Run in Parallel”const [users, posts] = await Promise.all([ fetchUsers(), fetchPosts(),]);Pattern Comparison
Section titled “Pattern Comparison”| Pattern | Pros | Cons |
|---|---|---|
| Callbacks | Simple | Callback hell |
| Promises | Chainable | Verbose |
| Async/Await | Readable | Needs try/catch |