Callbacks Promises Async Functions
Callbacks Promises Async Functions
Async Functions
Lionel KITIHOUN
September 16, 2023
● Beginners in JavaScript
3
● Slides
● Quizzes
Procedure
5
Synchronous vs
asynchronous
Promises Recap, Questions, etc.
programming
I II III IV V
6
Notice
● Threads
● Event loop (maybe a little 😉)
● Micro and macro tasks
7
Synchronous vs asynchronous
programming
Synchronous Programming
9
Search Tags in Text
10
Search Tags in Text II
11
Database Connection
<?php
$dsn = 'mysql:dbname=otakudb;host=127.0.0.1';
$cn = new PDO($dsn, 'buu', 'chocolate');
$query = 'select title, author, hero from mangas';
$rs = $cn->query($query);
foreach ($rs as $row) {
echo $row->title, $row->author, $row->hero;
}
$cn = null;
?>
12
Reading Lines from a File
ifstream in ("input.txt");
string line;
while (getline(in, line)) {
cout << line << endl;
}
cout << "No more line to read..." << endl;
13
The “Problem” with Synchronous Programming
The “problem” is that long running functions will block your program and it
can get stuck at some point, not enable to do something else.
14
Example: Open a Big File in an Editor
Maybe some of you have experienced it before. When you try to open a really
big text file in an editor, the editor freezes for a long time.
That’s because the program must wait until the entire contents of the file have
been loaded.
15
Blocking Code
Opening and reading data from a file, creating a connection and sending
queries to a database, downloading a file, are usually delegated to the OS
kernel which notifies the program once they are completed.
Which means that during the time these operations are handled by the kernel,
our program does nothing but wait.
16
Real-World Illustration
Imagine you are a young graduate and you want to continue your studies at a
top university in France or the USA. You submit your application to Campus
France for example.
Applications take six to nine months to process. What will do during this time?
17
Source: https://www.talkspace.com/blog/stop-procrastinating-how-to/
18
Source: https://stock.adobe.com
19
The World Is Async by Nature
When you order food on Gozem, or a new outfit from your tailor, you are busy
with other activities. When your order is ready they call you, or a delivery man
brings it to you.
You don’t waste your time on tasks that don’t fit your skills. You delegate them
to other people more qualified to do it, and you just want the result back.
That how the world is made. And some programming languages have
adopted this behaviour.
20
Asynchronous Programming
21
https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/
22
Asynchronous Programming with JS
23
Opening a File in Node
25
Definition
26
Not All Callbacks Are Asynchronous
27
Synchronous vs Asynchronous Callbacks
return n ** 2 // ...
}
}
28
Synchronous Callbacks
They are called immediately without delay by the function they are passed to.
29
Examples of Synchronous Callbacks
● Array.prototype.sort
● Array.prototype.filter
● Array.prototype.every
30
Array “filter” Method Example Implementation
function filter(cb) {
const selected = []
return selected
} 31
Asynchronous Callbacks
32
Async Callback Illustration
33
https://medium.com/gradeup/asynchronous-javascript-event-loop-1c8de41298dd
34
Examples of Asynchronous Callbacks
Usually, your callback is called asynchronously when your are dealing with
timers and HTTP requests.
● setTimeout
● XMLHttpRequest
● Most web APIs
35
https://www.freecodecamp.org/news/synchronous-vs-asynchronous-in-javascript/
36
First Quiz
37
Answers to The Quiz
Source: pinimg.com
38
Database access (Node)
40
Usual syntax
41
The “Problem” with Callbacks
It can happen that a lot of callbacks get nested, making the code hard to read
and maintain.
As an example, imagine that we want, for each manga in our database, to list
its characters, and for each character, to display his skills.
42
Nested Callbacks Illustration
db.on('open', () => {
db.all("select * from mangas where type = 'Shonen'", (err, mangas) => {
if (err) {
console.log('Error fetching mangas', err)
return
}
mangas.forEach(manga => {
const { id } = manga
db.each('select * from characters where manga_id = :id', { id }, (err, c) => {
db.all('select * from skills where character_id = :cid', { cid: c.id }, (err, skills) => {
// Work with the character and his skills
})
})
})
})
})
43
Callback Hell 😈
At the bottom of this code snippet, there is this nice looking succession of
closing brackets.
This lovely figure is called a callback hell or pyramid of doom and happens
when a lot of callbacks are nested.
This kind of code was common in the early days of JS and is usually hard to
deal with.
44
Source: giphy.com
45
https://wesbos.com/javascript/12-advanced-flow-control/69-refactoring-callback-hell-to-promise-land
46
Question
Have you ever dealt with a callback hell ? How did you manage to escape
from it?
47
Typical Use Case of Asynchronous Functions
In case of success, we want to process the result of the operation, and if the
operation errored, we want to know what went wrong.
48
A Nice Thing to Have
asynchronousFunction(...args)
.onSuccess(result => {
// Process the result...
})
.onFailure(err => {
// Take appropriate action...
})
49
And When We Need to Nest Callbacks
asynchronousFunction(args)
.onSuccess(fisrtResult => {
// Process `firstResult` and return data we will process further...
return secondResult
})
.onSuccess(secondResult => {
// Process `secondResult` and if needed, return something for next step...
return thirdResult
})
.onFailure(err => {
// If anything went wrong, the error will be handled here...
}) 50
The Promise of Better Async Code
I personally find that more readable and pleasant to code than nested
callbacks. And that what promises enable us to do.
51
Promises
52
Before Anything
53
Definition
54
Usage
55
Promise Illustration
Back to our japa example with Campus France. If after six months our
application is accepted, we will be happy, and leave for greener pastures. That
corresponds to the success of our promise.
On the other hand, if we are not accepted, the promise is not fulfilled and we
go to a fallback action. Continue our internship, get a fulltime job, or maybe try
#Canada2024. 😄
56
How to Use Promises
● Get one from a function that returns a promise like fetch or create a new
one using the Promise constructor.
● Attach handlers to the Promise object via its then, catch, and finally
methods.
57
First example: Fetch API
fetch('https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/25.png')
.then(response => {
console.log(`Received response: ${response.status}`);
})
.catch(err => {
console.error('Something went wrong', err)
})
58
The Promise Constructor
When the function ends, its notifies the promise about its status and the
promise asynchronously calls the callbacks you attached to it via its then and
catch methods.
59
The Notification Mechanism
To notify the promise about its termination, the executor function uses two
callbacks it received from the promise constructor.
60
The Promise Constructor
61
The “then” Method
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult1 = T, TResult2 = never>(
onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null,
onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null
): Promise<TResult1 | TResult2>
62
The “catch” Method
/**
* Attaches a callback for only the rejection of the Promise.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of the callback.
*/
catch<TResult = never>(
onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null
): Promise<T | TResult>;
63
The “finally” Method
/**
* Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The
* resolved value cannot be modified from the callback.
* @param onfinally The callback to execute when the Promise is settled (fulfilled or rejected).
* @returns A Promise for the completion of the callback.
*/
finally(onfinally?: (() => void) | undefined | null): Promise<T>
64
Example: Creating a Promise
readFile('/path/to/file', (err, data) => { const promise = new Promise((resolve, reject) => {
if (err) readFile('/path/to/file', (err, data) => {
console.log('Unable to read file', err) if (err)
else reject(err)
console.log('File content', data) else
}) resolve(data)
}) })
})
promise.then((data) => {
console.log('File content', data)
})
promise.catch(err => {
console.log('Unable to read file', err)
})
65
Chaining Promises
The then and catch methods return a Promise, allowing us to chain promises and
execute back to back asynchronous operations in a cleaner way than nested callbacks.
Source: stock.adobe.com 66
Back to Back Async Operations
67
Sqlite Connection With Promises
function openDb() {
return new Promise((resolve, reject) => {
const db = new sqlite3.Database('/path/to/db.sqlite', (err) => {
if (err) reject(err)
})
db.on('open', () => resolve(db))
})
}
68
Getting Shonen Characters
openDb()
.then(db => getMangas(db, 'Shonen'))
.then(({ db, mangas }) => getCharacters(db, mangas))
.then(characters => {
characters.forEach(c => {
// ...
})
})
.catch(err => console.error(err))
70
Important Details
71
Executor Start and Promise Constructor Return
72
Third Quiz: Find This Program Output
console.log('3')
73
Vocabulary
● Pending Promise
● Resolved Promise
● Rejected Promise
● Settled Promise
74
Pending Promise
Source: stock.adobe.com 75
Resolved Promise
Source: www.standard.co.uk 76
Rejected Promise
77
Settled Promise
Source: istockphoto.com 78
Promise static Methods
● Promise.resolve
● Promise.reject
● Promise.all
● Promise.any
● Promise.race
● Promise.allSettled
79
Promise.all
Source: culturedvultures.com 80
Promise.any
Source: istockphoto.com 81
Promise.race
Source: https://statathlon.com
82
Async Functions
83
Benefits
They were introduced in the language with async and await keywords.
84
The async Keyword
85
Async Function Example
86
Async Function Example II
87
The await Keyword
88
Promise Chain vs Async Functions: First Example
getPokemon()
89
Promise Chain vs Async Functions: Second Example
90
Recap
91
Recap
92
References
93
References
94
References II
95
96