JS12 ClassNotes
JS12 ClassNotes
lege
l
async await >> promise chains >> callback hell
a Co
Apn
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
ge
A callback is a function passed as an argument to another function.
le
Col
pna
A
Callback Hell
ge
Callback Hell : Nested callbacks stacked below one another forming a pyramid structure.
(Pyramid of Doom)
olle
na C
p
This style of programming becomes difficult to understand & manage.
A
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
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
promise.then( ( res ) => { .... } )
pna
A
promise.catch( ( err ) ) => { .... } )
Async-Await
async function always returns a promise.
leg
async function myFunc( ) { .... }
e
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