Js Sem2 Promises
Js Sem2 Promises
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.
4
Pre-discussed: Ways to implement
There are three main ways to implement asynchronous programming in JavaScript:
Async Programing
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.
6
Pre-discussed: Callbacks
Let’s add a delay of 2000 milliseconds before callback executes using setTimeout().
7
Callbacks: Don’t make function async
Callbacks don’t make functions asynchronous!
Output:
Hello, Alice
Goodbye!
8
Callbacks: Handle async operations
Let’s have a look at end to end comparison of performing async operations without
and with callbacks.
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.
11
Challenge with Callbacks
Callbacks facilitate asynchronous operations, but when multiple operations need to be
performed sequentially, they can lead to callback hell.
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.
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.
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()
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()
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
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
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
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.
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.
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.
34
.catch(): Example
It might be possible that error occurred while consuming the promise which can be
caught using the .catch() block.
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.
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.
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
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.
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.
52
Asynchronous Flow in Promises
In promises we chain the tasks using then() and catch() blocks. Hence program is
executed in chain like manner.
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.
Name
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.
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