JavaScript Promises

JavaScript Tutorial

JavaScript Promises

In JavaScript Promises is an object representing the eventual completion or failure of an asynchronous operation.
It allows handling async tasks more cleanly than callbacks.


Promise States

StateDescription
PendingInitial state, operation not completed yet
FulfilledOperation completed successfully
RejectedOperation failed

Creating a Promise


 


Consuming a Promise


Example: Simulate Async Task


 


Chaining Promises

You can chain .then() to perform multiple steps sequentially:


 


Promise.all()

Promise.all() runs multiple promises in parallel and waits for all to complete.


 


Promise.race()

Promise.race() returns the result of the first promise to settle.


 


Best Practices

  • Always handle errors with .catch()

  • Chain promises instead of nesting callbacks

  • Use Promise.all() for parallel async operations

  • Consider using async/await for cleaner syntax


 Summary Table

ConceptMethod
Create Promisenew Promise((resolve, reject) => {})
Resolveresolve(value)
Rejectreject(error)
Handle success.then(result => {})
Handle error.catch(error => {})
Run multiplePromise.all()
First completedPromise.race()

You may also like...