0% found this document useful (0 votes)
22 views

JS12 ClassNotes

The document discusses synchronous and asynchronous code in JavaScript. It explains callbacks, callback hell, promises, and async/await. Promises are introduced as a solution to callback hell. Async functions always return promises and await pauses async function execution until a promise settles.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

JS12 ClassNotes

The document discusses synchronous and asynchronous code in JavaScript. It explains callbacks, callback hell, promises, and async/await. Promises are introduced as a solution to callback hell. Async functions always return promises and await pauses async function execution until a promise settles.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

What this chapter is about?

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

*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
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

You might also like