0% found this document useful (0 votes)
2 views

Master JavaScript Promises and Async_Await Easily

The document explains JavaScript Promises, detailing their lifecycle states (pending, fulfilled, rejected) and how to use them to manage asynchronous operations effectively. It covers methods like .then(), .catch(), and .finally() for handling results and errors, as well as techniques for chaining promises and using async/await for cleaner code. Additionally, it discusses handling multiple promises simultaneously with methods like Promise.all, Promise.race, and Promise.any.

Uploaded by

Dhruv Takkar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Master JavaScript Promises and Async_Await Easily

The document explains JavaScript Promises, detailing their lifecycle states (pending, fulfilled, rejected) and how to use them to manage asynchronous operations effectively. It covers methods like .then(), .catch(), and .finally() for handling results and errors, as well as techniques for chaining promises and using async/await for cleaner code. Additionally, it discusses handling multiple promises simultaneously with methods like Promise.all, Promise.race, and Promise.any.

Uploaded by

Dhruv Takkar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

No more callback

hell
Shivendra Dwivedi
@shivendra-dwivedi
Promise:
It is a javaScript object which represents the eventual
completion or failure of an asynchronous call or
operation.
Initially the result of the Promise is undefined when
asynchronous operation starts.
Syntax: executer function

resolve method reject method

Example:

Note: Promise object has two internal properties


“result” and “state”.
@Shivendra Dwivedi
Life cycle of a promise:
A Promise goes through three states during its
lifecycle:
Pending -> The initial state; the promise is waiting for the
result.
Fulfilled -> The operation was successful, and the promise
returns a value.
Rejected -> The operation failed, and the promise returns
an error.

e)
alu
e(v
olv
res

rej
ec
t(e
rro
r)

Note: A Promise can call only one resolve or reject.


Once settled, its state is final.

@Shivendra Dwivedi
Why/When to Use a promise:
Use it when you have an operation that completes in
the future—either successfully or with an error.
It helps to avoid callback hell and makes async code
cleaner.
Example:

callback

callback

callback

Solution:

returning a
promise

handling the
promise

@Shivendra Dwivedi
Consumers .then(), .catch():
.then()
Used to handle the successful result of a Promise.
Can also take a second argument to handle errors
(though .catch() is preferred).
Returns a new Promise, so it's chainable.

.catch() – Used for Error Handling


Handles rejected Promises (errors).
Can be chained after .then().

Note: .then(null, onRejected) and .catch(onRejected)


are similar, but .catch() also catches errors inside
.then().

@Shivendra Dwivedi
Cleaning up with finally():
Runs after a Promise is settled (either resolved or
rejected).
Used for cleanup tasks like hiding loaders, closing
database connections, etc.
Doesn’t receive the Promise result.

Promise Chaining:
A technique where we connect multiple .then() calls,
so the output of one becomes the input for the next.
Use it when you want to run tasks one after another,
and each depends on the previous one.
Example: User login → fetch profile → show
dashboard.

@Shivendra Dwivedi
chaining .then()
calls

Important: Each function in the chain must return a


promise — this keeps the flow async and connected.

Quick Promises:
Promise.resolve():
Returns a promise that is already resolved with the
given value. Use it to mock success or return resolved
value.

Promise.reject():
Returns a promise that is already rejected with the
given error. Use it to mock failure or simulate errors.

@Shivendra Dwivedi
calling .resolve()

calling .reject()
handling resolved promise

handling rejected promise

Handling multiple promises simultaneously


For this we have 4 methods Promise.all/ .allSettled/
.race/ .any .

Promise.all([P1, P2, P3, ...])


Waits for all promises to resolve and fails if any one of
the given promises rejects.
Use When: All results are required (e.g., load user +
posts + comments together).

@Shivendra Dwivedi
All resolve

Promise.allSettled([P1, P2, P3, ...])


Waits for all promises to settle (resolve or reject). It
never fails, it returns the status of each promise.
Use When: You want results + errors (e.g., batch API
calls with mixed outcomes).

rejects in 1 second

@Shivendra Dwivedi
no catch block

Promise.race([P1, P2, P3, ...])


Waits only for the first promise to settle (either
resolve or reject). Returns the result or error of the
first settled promise.
Use When: Speed matters (e.g., loading from
multiple servers/CDNs).

settles first in 1 second

@Shivendra Dwivedi
Promise.any([P1, P2, P3, ...])
Waits only for the first promise to resolve . Returns
the result by the 1st resolved promise or “All promises
were rejected” if all given promises reject.
Use When: You only care about first success (e.g.,
querying backup APIs).

1st resolved promise in 2 seconds

@Shivendra Dwivedi
Async : A keyword used to declare an asynchronous
function that always returns a Promise.

Await : Used inside async functions to pause the


execution until the awaited Promise settles (either
resolves or rejects).
Syntax:

Example:

Execution pauses
till promise
resolves/rejects.

@Shivendra Dwivedi
Why/ When to use async/await
There are two major reasons :
Messy chaining with multiple .then() → leads to
"Promise Hell".
No pause in flow — next lines execute before the
async task finishes.
More logic = more
.then() chaos

With async/await, better readability and easier


debugging. Awaits each step before moving to next.

easier error
handling

@Shivendra Dwivedi
Error handling in async/await
Use try...catch to handle errors. Wrap the awaited code
in the try block, use catch to handle errors, and finally
for cleanup tasks that run regardless of success or
failure.

error-prone code

catching the errorse

cleaning things up

@Shivendra Dwivedi
Resolving Multiple Promises in the Same
Async Function
Code above await runs synchronously.
At each await, JS checks if the Promise is resolved:
If not: function suspends, browser continues.
Once resolved: function resumes from where it
paused.
This pause-resume cycle happens for each awaited
promise.
If the same promise is awaited again, JS won’t
suspend , it immediately resumes since the promise
is already resolved.

First Promise, resolves in 2 sec

Second Promise, resolves in 3


sec

@Shivendra Dwivedi
logs immediately

paused here for 2


sec

paused here for 3


sec

Output:

Note: DevTools debugger might not visually show it


leaving, but under the hood — this is exactly what
happens.

@Shivendra Dwivedi
“await” outside async function
Yes, but only at top-level of ES modules in modern
environments (ES2022+ / Node.js). This is called Top-
Level Await — allows await without wrapping in async
function

Module

at top level

catch() anywhere in .then() chain?


We can use .catch() in the middle of a .then() chain to
handle specific errors up to that point. It doesn’t
have to be at the end.
Middle catch() handles only errors from above, not
from later .then()s.

@Shivendra Dwivedi
throws an error

catches the error from Step 3

Use Promises for clean async logic


Chain .then() or use async/await for readability
Handle errors with .catch() or try...catch"

@Shivendra Dwivedi
Was this helpful?

& Follow for more


JavaScript tips & tricks!
Shivendra Dwivedi
@Shivendra-Dwivedi

Comment

You might also like