Instructor:: Humaira Waqas

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

Lecture 4

Instructor: Humaira Waqas

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 1


TOPICS
• Why JavaScript as a Server-side language?
• Node.Js
• Non-Blocking I/O, Concurrency
• Callback Function
• Callback Hell
• Event Loop
• Call Stack
• Message Queue

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 2


WHY JAVASCRIPT AS A SERVER-SIDE LANGUAGE?
Familiarity
Ubiquity
Need one specialization
Non-Blocking Asynchronous I/O
Before discussing this concept in detail
let's see some problems with the I/O

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 3


WHY JAVASCRIPT AS A SERVER-SIDE LANGUAGE?
Problems with I/O
Web servers have to execute some I/O
 Reading from a disk
 Querying a database
 Communicating with another web server
 Even modern computers I/O is still the slowest part of any system
 Disk and Network I/O are slower than RAM and CPU cache.
 Servers have to respond to hundred of thousands of requests
per minute at the cost of performance

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 4


WHY JAVASCRIPT AS A SERVER-SIDE LANGUAGE?
Client – Server Request Cycle (I/O)
 Request comes to the web server
 Web server requests the database (DB) using a
Query where the DB is hosted on another
server
 The DB engine runs the query and assembles the results
 The DB server responds to our web server with the results
 The web server receives the query results and turns them to JSON
 The web server reads from the local file system to find an appropriate HTML document to
display the results
 The server responds to the request and returns HTML with all the requested information

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 5


WHY JAVASCRIPT AS A SERVER-SIDE LANGUAGE?
I/O latency is apparent during several steps
 Network, disk, and disk approximately 322,000,000 cycles for blocking
I/O operations
 I/O activity that blocks other processing from happening in a running
program is a blocking I/O
 Any public facing web server needs to be able to serve many
thousands of concurrent requests and requires extremely high uptime
and low latency

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 6


WHY JAVASCRIPT AS A SERVER-SIDE LANGUAGE?
Scalability issues
 Web servers built with traditional programming languages like Java or PHP solve
scalability using
 Multi threading / parallel processing, and solve the latency and I/O issues
 But these applications are:
 Complicated
 Require more hardware as the load on the server increases
 Threads and parallel processing isn’t free
 Companies with finite number of resources are handicap

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 7


NODE
JavaScript (and Node) by convention is non-blocking language
It has built-in solution for I/O issues, i.e., Callback function.
Callback
 A function that is executed when I/O operations finish or produce an error.
 Instead of waiting and create latency for other users, an operation starts, and a
callback function is supplied
 When the I/O is complete the callback executes
 Although there is still a delay in waiting for the I/O to finish, but other logic can
execute during this time

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 8


NODE
Recall AJAX
 A request is made (network I/O) and we supply a callback to it
 The browser window is not blocked, and the user is still free to click on any element on
the page
 When the request completes, the callback is executed
Node
 Node’s core I/O functions offer asynchronous as well as synchronous versions
 This does not mean that it will speed up requests to the database server
 It just prevents the I/O activity from blocking additional service requests
 It allows web servers to handle more concurrent requests without requiring
additional hardware or configuration

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 9


NODE
JavaScript (JS) is synchronous by nature
JS is single threaded (code cannot create new threads and run in parallel)
const a = 1
const b = 2
const c = a * b
console.log(c)
doSomething()

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 10


NODE
Callback
 We define an event handler for the click event
 The event handler accept a function which will be called when the event is triggered
 A callback is a simple function that is passed as a value to another function and will
only be executed when the event happens.

document.getElementById('button').addEventListener('click', () => {

//item clicked
})

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 11


NODE
Callback
window.addEventListener('load', () => {
//window loaded
//do what you want
})

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 12


NODE
• Callbacks are used everywhere, not just in DOM events
• One common example is by using timers:

setTimeout(() => {
// runs after 2 seconds
}, 2000)

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 13


NODE
Callback
const xhr = new XMLHttpRequest()
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if(xhr.status === 200){
console.log(xhr.responseText);}
else{
console.error('error’);}
}
}
xhr.open('GET', 'https://yoursite.com')
xhr.send()
WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 14
NODE
Handling errors in Callbacks
Common strategy is that the first parameter in
any callback is the error object
 Error-first callbacks

fs.readFile ('/file.json', (err, data) => {


if (err) {
//handle error
console.log(err)
return
}
//no errors, process data
Else{ console.log(data)}
}
)
WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 15
NODE
Problem with Callbacks
 Every callback adds a level of nesting which adds complexity very quickly

window.addEventListener('load', () => {
document.getElementById('button').addEventListener
('click', () => {
setTimeout(() => {
items.forEach(item => {
//your code here
})
}, 2000)
})
})
WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 16
NODE
Problem with Callbacks
This is an example with 4 level callbacks, often termed as Callback hell
Advance Level Alternatives to callbacks
 Promises and Async/Await

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 17


NODE
Quick Recap to Callbacks
• Callbacks are just the name of a convention for using JavaScript functions.
• There isn't a special thing called a 'callback' in the JavaScript language, it's just a
convention.
• Instead of immediately returning some result like most functions, functions that use
callbacks take some time to produce a result.
• The word 'asynchronous', aka 'async' just means 'takes some time' or 'happens in the
future, not right now’.
• Usually, callbacks are only used when doing I/O, e.g., downloading things, reading
files, talking to databases, etc.

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 18


NODE
Remember callback as: Call you back later when the work is complete
• The biggest hurdle people have when trying to understand callbacks is understanding
the order that things execute as the program runs
• The order in which things happen does not read top-to-bottom, it jumps around based
on when things complete, that’s why it is called Callback hell.

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 19


NODE
Fix Callback hell
Give functions names instead of keeping them anonymous
 It makes code easier to read
 Allows you to move the functions and reference them by their names
 In case exceptions happen, you will get stack traces that reference actual function
names instead of “anonymous”
Modularize
 Write small modules that each do one thing and assemble them into other modules
that do a bigger thing. This means that you don’t get into callback hell if you don’t go
there.
Handle every single error
WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 20
NODE
Advance Solutions to avoid Callback hell
•Use Promises
•Generators
•Async functions

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 21


NODE
Event loop
We know Node.js code runs on a single thread, which means one thing is happening at
a time
There is an event loop for every browser tab, to isolate and avoid a web page with
infinite loops or heavy processing to block your entire browser
Event loop continuously checks the call stack and executes each one in order
It adds any function call it finds to the call stack and executes each one in order
The browser looks up the function names in the call stack to inform you which function
originates the current call

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 22


NODE
The Call Stack
 It is a LIFO (last In, First Out) stack
 The event loop continuously checks the call stack and executes each one in order

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 23


NODE
Event loop example
• When this code runs, first foo() is called.
• Inside foo() we first call bar(), then we call baz()

const bar = () => console.log('bar')


const baz = () => console.log('baz')
const foo = () => {
console.log('foo')
bar()
baz()
}
foo()

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 24


NODE
const bar = () => console.log('bar')
const baz = () => console.log('baz')
const foo = () => {
console.log('foo')
bar()
baz()
}
foo()

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 25


NODE
Event loop example
• When this code runs, first foo() is called.
• Inside foo() we first call bar(), then we call baz()
Simple ? Not exactly……
Remember Callback functions …..?
• They are maintained in Message Queue

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 26


NODE
Message Queue
• Callbacks
The event loop gives priority to the call stack (process everything it finds in
the call stack)
After everything is processed in the call stack, it goes to the message queue
Job Queue
Promises use Job Queue (a way to execute the result of an async function as
soon as possible)

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 27


NODE
Event loop example 2
const bar = () => console.log('bar')
const baz = () => console.log('baz')
const foo = () => {
console.log('foo')
setTimeout(bar, 0)
baz()
}

foo()

When setTimeout() is called, the Browser or


Node.js starts the timer.
Once the timer expires, in this case immediately as
we put 0 as the timeout, the callback function is
put in the Message Queue. WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 28
NODE
Recap … Message Queue
 User initiated events like click, keyboard, fetch responses are queued before your
code gets the opportunity to react to them
 Message queue is entertained after the call stack is empty

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 29


DISCUSSION

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 30

You might also like