0% found this document useful (0 votes)
28 views59 pages

Js Sem2 Promises

This lecture introduces JavaScript Promises, explaining their necessity over callbacks for managing asynchronous operations. It covers the concept of promises, their states (pending, fulfilled, rejected), and methods like .then(), .catch(), and .finally() for handling outcomes. The lecture also discusses practical usage scenarios such as fetching data and setting timers with promises.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views59 pages

Js Sem2 Promises

This lecture introduces JavaScript Promises, explaining their necessity over callbacks for managing asynchronous operations. It covers the concept of promises, their states (pending, fulfilled, rejected), and methods like .then(), .catch(), and .finally() for handling outcomes. The lecture also discusses practical usage scenarios such as fetching data and setting timers with promises.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

The Complete Lecture 10:

Javascript Course
Introduction to
Promises
-Bhavesh Bansal

@newtonschool
1
Table of Contents
● Callbacks vs Promise: Need for promise
● Understanding Promises
○ Promises in Javascript
○ Basic Promise Usage
● Creating Promises
○ Promise Constructor
○ Promise Methods: then(), catch() and finally()
● Handling Promise States
resolve reject pending
● Pending ● Pending

○ ○ ○
● Error Handling
2
Why do we need Promises?

3
Pre-discussed: Async Programming
Asynchronous programming lets tasks run independently, allowing your program to
continue other tasks while waiting for long operations to finish.

Here, the program


sends a request to the
server and, while
waiting for the
response, continues
accepting and
processing user
inputs.

4
Pre-discussed: Ways to implement
There are three main ways to implement asynchronous programming in JavaScript:

Async Programing

Callbacks Promises Async/Await

5
Pre-discussed: Callbacks
In simple terms, a callback is just a function that you give to another function. The
receiving function will then decide when and how to execute.

Here it is upto task1() function


when and where it executes
callback function. Here it is
executing it immediately but that
is not always the case.

6
Pre-discussed: Callbacks
Let’s add a delay of 2000 milliseconds before callback executes using setTimeout().

Here we are adding a delay


inside task1 function using
setTimeout().

7
Callbacks: Don’t make function async
Callbacks don’t make functions asynchronous!

Output:
Hello, Alice
Goodbye!

Here, sayGoodbye() executes


immediately after console.log().
There's nothing asynchronous
happening.

8
Callbacks: Handle async operations
Let’s have a look at end to end comparison of performing async operations without
and with callbacks.

Can you tell why??

Why?

9
Callbacks: Handle async operations
Here fetch() does return a value, but since we are not using callbacks, we can’t add a
task which only needs to happens after fetch operations completes.

We expect to get a
value immediately after
calling getUserData(),
but since fetch() is
asynchronous, the data
isn’t available yet, so
we get undefined.

10
Callbacks: Handle async operations
Instead we need to pass a function to which gets invoked only after fetch() completes
its execution. And that function is called Callback Function.

Callback function got received

Callback function gets invoked


only when fetch operation
completes

Passing the callback function


to getUserData() function

11
Challenge with Callbacks
Callbacks facilitate asynchronous operations, but when multiple operations need to be
performed sequentially, they can lead to callback hell.

Callback hell makes


code hard to debug
and update, leading to
poor scalability.

12
Promises: a more structured way
Promises are built on callbacks, but they offer a more structured and manageable
way to handle asynchronous operations compared to using callbacks directly.

.then()
A Promise essentially wraps Callbacks
an asynchronous operation chained with
and provides two callback promise
.catch()

13
Understanding the Promises

14
Have you ever made a promise?
If you did, then you must know how valuable promises are. A promise in real life is
a commitment or guarantee made by someone.

Sadly, few promises


remain unfulfilled.

15
Stages of promise
If you did, then you must know how valuable promises are. A promise in real life is
a commitment or guarantee made by someone.

16
Promises in Javascript
A promise is a commitment in programming—a guarantee that something will
happen in the future but not an immediate action. It’s a placeholder for future work.

Promise Fulfilled
Pending
State
After specific
period of time

Promise
Rejected

17
Different promise states
Promises in Javascript exist in three states: pending, fulfilled, and rejected.

Initially, a promise remains in a


pending state, and after some
time it either gets
resolved/fulfilled or rejected.

18
Creating Promises

19
Promise: constructing a promise
To create a promise in JavaScript, you use the Promise constructor. The promise
constructor receives two functions as arguments: resolve() and reject()

The resolve function is called when


the promise is successfully
fulfilled.

The reject function is called when


the promise is rejected.

20
Promise: Using Promise Constructor
To create a promise in JavaScript, you use the Promise constructor. The promise
constructor receives two functions as arguments: resolve() and reject()

Received resolve and


reject functions as
arguments

21
Promise: resolve()
The resolve method in JavaScript is a static method of the Promise object. It is used
to create a promise that is resolved with a given value.

resolve() function’s
work is to finish the
task and provide a
return value.
Resolved the task and provided
the work data as return value

Fail/rejected reject() function’s


Promised to complete the task and return
in meeting fail/error
work is to return an
message appropriate error
message
22
Promise: resolve()
Let’s have a look at a dummy example:

On successful
resolution of
promise, resolve()
returns a value.
For simplicity, we
are returning a
success message.

23
Promise: reject()
It might be possible that a promise can’t be delivered and you need to provide an
explanation and, in JavaScript, an error message.

resolve() function
work is to finish the
task and provide a
return value.
Resolved the task and provide
the work data as return value

reject() function work


Fail/rejected is to return an
Promised to complete the task and return
in meeting appropriate error
fail/error
message
message

24
Promise: reject()
Let’s have a look at a dummy example:

On failure to
resolve a promise
reject() returns an
error message.
For simplicity we
are returning a
failure message..

25
Promise: pending()
Before either promise gets resolved or rejected, there is some wait period. This
wait period is called pending state of promise

Pending State

Resolved the task and provided


Wait the work data as return value
Period

Fail/rejected
Promised to complete the task and return
in meeting fail/error
message

26
Promise Creation: Example 1
Let’s understand promises with a simple example:

Using resolve() to
fulfill the promise

Using reject() to
reject the promise

27
Promise Creation: Example 2
Let’s take a more practical example:

Success Or Failure

resolve reject

28
Handling the Promise

29
Promises: Handling Promise Outcomes
As we have learned, a promise is initially in a pending state, and then after a while it
either gets resolved or rejected.

ture
cap
alue
ed v
What to do with Resolv
resolved and
rejected outcomes
Han
dle
Erro
r

30
Promises: Bridging Hope and Reality
We hope a promise resolves/fulfilled and gives us a value to work with in the “then”
block. However, if it gets rejected, we handle it in the “catch” block.

We can add
We capture finally at the end
resolved value (optional)
using .then()
block

.finally()

Or else we
handle error
Finally runs, regardless of
inside .catch()
the promise's result.
block

31
Promise: Using the .then() block
The .then() block handles data after resolution in a promise chain by capturing it and
allowing further processing.

Promise returns the value

We can use the returned


value from Promise inside
.then() block

32
.then(): Example
The .then() block is used to handle the successful resolution of a promise, capturing
the returned value and allowing further processing or actions.

Here we are using .then() block to


capture the resolved value

33
Promise: Using .catch() block
The .catch() block handles errors or rejections in a promise chain, ensuring that any
issues during the operation are caught and managed gracefully.

.catch() is indeed added


after the last .then() block in
most cases to handle any
errors that occur while
consuming the promise.

34
.catch(): Example
It might be possible that error occurred while consuming the promise which can be
caught using the .catch() block.

Here we are capturing


error while consuming
the promise.

35
Promise: Using .finally() block
It is possible to chain a block that runs regardless of whether the promise is resolved
or rejected using .finally() block.

36
.finally(): Example
It is possible to chain a block that runs regardless of whether the promise is resolved
or rejected using .finally() block.

finally() block

37
Why do we need Promises??
In the previous lecture we learned that callbacks can be used to implement async
programming; then why do we need to make promises?

Seems
Cluttered
Callback

I can perform
async
operations

38
Why do we need Promises??
Callbacks can often lead to cluttered and unreliable code due to nested functions. It is
better to chain tasks, where one task starts after the previous one ends, and this is
achieved using promises.

39
Callbacks vs Promises vs Async/await
We use callbacks for simple asynchronous tasks, promises for chaining more complex
tasks, and async/await for writing asynchronous code that appears sequential.
Promise Basic Usages

41
Basic Promise Usage
Promises in JavaScript simplify handling asynchronous operations. Here are
common use cases:

Usages

Setting up
Fetching Data Reading Files Many More..
Timers

● setTimeout()
We will learn it later in detail,
● setInterval()
here we will have brief overview.

42
Usage: Fetching Data
We use fetch api to get data from the server.

Fetching data from server is an


async operation so we used
promise for it.

Here we conditionally
rejected/resolved the
promise

43
setTimeout and setInterval

with Promises

44
Pre-discussed: setTimeout
setTimeout is a JavaScript function that executes a callback function after a specified
delay (in milliseconds).

Syntax:

(greet,

Callback function

45
Pre-discussed: setTimeout Example
We can print specific message after a certain period of time using setTimeout.

Here we get output after 2000


milliseconds i.e. 2 secs

Output:

Hello

46
setTimeout wrapped in a Promise
There might be instances where you need to set up timers in JavaScript. In such cases,
you can use setTimeout in combination with promises

Creating and returning a


promise

Calling the function


returning the promise and
consuming the returned
promise

47
Pre-discussed: setInterval
setInterval is a JavaScript function that repeatedly executes a specified callback
function at fixed time intervals (in milliseconds).

Syntax:

(greet,

48
Pre-discussed: setInterval example
Here we are printing and updating message count every 1000 milliseconds. The
setInterval() function returns a unique identifier, known as an interval ID, which is
stored to later clear the interval

Output:

Message 1
Message 2
Message 3
..
..

49
Usage: Setting up timers (SetInterval)
In similar fashion you can use setInterval if you want a task to be repeated after
certain interval of time.

Creating and returning a


promise

Calling the function


returning the promise.

50
Understanding Asynchronous
flow in Promises

51
What is Asynchronous Flow?
Asynchronous flow allows programs to perform tasks concurrently without blocking
other tasks. It enables operations such as fetching data, reading files, or waiting for
user input without freezing the program.

Unlike sync operations


async operations do not
need to wait till the other
task complete its
execution.

52
Asynchronous Flow in Promises
In promises we chain the tasks using then() and catch() blocks. Hence program is
executed in chain like manner.

Corresponding block executes


only after the execution of block
previous block.

53
Workshop: Question
You're building a registration form where users submit their name, email, and age. The
input data needs to be validated asynchronously, such as if name is valid, checking if
the email is already registered (with a delay) and ensuring the age is valid.

How would you implement using promises?


Can you
validate data?

Name

Email

Age

54
Workshop: Solution
Let’s write a function using promises for validating name asynchronously.

Write functions to
validate email and age
by yourself.

55
Workshop: Solution
Let’s write validation functions for email and age too.

Validating Email Validating Age

56
In Class Questions

57
References
1. MDN Web Docs - JavaScript: Comprehensive and beginner-friendly documentation for
JavaScript.
https://developer.mozilla.org/en-US/docs/Web/JavaScript
2. Eloquent JavaScript: A free online book covering JavaScript fundamentals and advanced topics.
https://eloquentjavascript.net/
3. JavaScript.info: A modern guide with interactive tutorials and examples for JavaScript learners.
https://javascript.info/
4. freeCodeCamp JavaScript Tutorials: Free interactive lessons and coding challenges to learn
JavaScript.
https://www.freecodecamp.org/learn/

58
Thanks
for
watching!

59

You might also like