Topics — Asynchronous Programming .
What this chapter is about?
lege
l
async await >> promise chains >> callback hell
Co
What this chapter is about
a
It’s about handling tasks that take time, like:
n
Fetching data from an API
p
Reading files
A
Waiting for a timer
JavaScript doesn’t wait — it runs asynchronously.
Sync in JS
Synchronous
Synchronous means the code runs in a particular sequence of instructions given in the program.
e
Each instruction waits for the previous instruction to complete its execution.
lleg
Co
Asynchronous
na
Due to synchronous programming, sometimes imp instructions get
Ap
blocked due to some previous instructions, which causes a delay in the UI.
Asynchronous code execution allows to execute next instructions
immediately and doesn't block the flow.
Callbacks
lege
A callback is a function passed as an argument to another function. function greet(name, callback) {
ol
[Link]("Hello " + name);
C
callback(); // calling the callback function
}
na
function sayBye() {
Ap
[Link]("Goodbye!");
}
greet("Tarun", sayBye);
Hello Tarun
Goodbye!
Callback Hell
ge
Callback Hell : Nested callbacks stacked below one another forming a pyramid structure.
(Pyramid of Doom)
olle
a C
setTimeout(() => {
n
[Link]("Task 1 done");
p
This style of programming becomes difficult to understand & manage.
A
setTimeout(() => {
[Link]("Task 2 done");
setTimeout(() => {
setTimeout(callbackFunction, delay); [Link]("Task 3 done");
setTimeout(() => {
setTimeout(callback1) [Link]("Task 1 done"); setTimeout(() => {
└── setTimeout(callback2) }, 1000); [Link]("Task 4 done");
└── setTimeout(callback3) }, 1000);
└── setTimeout(callback4) The arrow function
}, 1000);
() => {
[Link]("Task 1 done");
}, 1000);
}
is passed as an argument to setTimeout. }, 1000);
Promises
Promise is for “eventual” completion of task. It is an object in JS.
e
It is a solution to callback hell.
lleg
Co
let promise = new Promise( (resolve, reject) => { .... } )
a
Apn Function with 2 handlers
*resolve & reject are callbacks provided by JS
Promises
A JavaScript Promise object can be:
lege
Pending : the result is undefined
Col
Resolved : the result is a value (fulfilled) resolve( result )
pna
Rejected : the result is an error object reject( error )
A
*Promise has state (pending, fulfilled) & some
result (result for resolve & error for reject).
Promises
ge
.then( ) & .catch( )
olle
C
[Link]( ( res ) => { .... } )
pna
A
[Link]( ( err ) ) => { .... } )
async makes a function return a Promise, and await pauses execution until the Promise resolves.
Async-Await
async function always returns a promise.
async function myFunc( ) { .... }
lege
Col
na
await pauses the execution of its surrounding async function until the promise is settled.
Ap
IIFE : Immediately Invoked Function Expression
lege
l
IIFE is a function that is called immediately as soon as it is defined.
a Co
Apn