INFO 30005
Web Information Technologies
JavaScript based on content by Ronal Singh
Copyright By Assignmentchef assignmentchef
Part A: Functions
function name(parameter1, parameter2, parameter3) {
keyword function
// code to be executed
return someValue
Ways to declare
function product(a, b) { return a * b;
const product = function(a, b) {
return a * b;
const product = (a, b) => { return a*b }
// arrow function
block of code
return value
Using functions
// declare the function
function product(a, b) {
return a * b;
arguments block of
// call the function
let result = product(3, 4) // 12 code
// function as value of variable
let myFunction = product
result = myFunction(3,4)
return value
Combining functions
// declare two functions
const product = (a, b) => { return a * b }
const sum = (a, b) => { return a + b }
// combined function calls
result = sum ( product(3,4), product(5,6) ) // 42
// function as input to another function
const double = (x) => {return x*2}
double(2) // 4
[1,2,3].map(double) // [2,4,6]
[1,2,3].map( (x) => {return x**2} ) // [1,4,9], uses literal [1,2,3].forEach( element => console.log(element + 2) )
Return, try, catch
// return and throw ends the function immediately
const quotient = (dividend, divisor) => { if (divisor == 0)
throw(divide by zero error)
return (dividend / divisor)
try { // attempt this work, but prepare to catch errors result = quotient(5,0)
console.log(result)
catch (e) { // caught an error
console.error(error detected: , e) }
Part B: Asynchronous
programming
Asynchronous programming in JS
To improve performance in networked applications, (long- running) input/output does not block JS programs.
(This means that statement n+1 in your program may start before statement n has finished!)
How can programmers manage this?
JS handles asynchronous processing in 3 ways: callbacks
promises
async/await
takes time to process
return value later
1. Callbacks
1. One approach to asynchronous programming
2. Slow actions take an extra argument, a callback function 3. After the action finishes, the callback function is called
Here is a web page that fetches some data
Callback function
This works!
but what if statement n+1 needs n to have finished?
statement n+1 may start before n has finished
// normal sequential execution of program statements
console.log(// normal sequential execution of program statements)
console.log(one) console.log(two) console.log(three)
// now make the second statement asynchronous
console.log(// now make the second statement asynchronous)
console.log(one)
setTimeout( ()=>{console.log(two)}, 2000 ) console.log(three)
Controlling sequence via nested callbacks
// prevent out-of-sequence
console.log(//prevent out-of-sequence) const one = () => {console.log(one)} const two = () => setTimeout( ()=>{
console.log(two)
three() // the next function is INSIDE this callback }, 3000
const three = () => {console.log(three)}
// start executing statements one, two and three ..
one() two()
Potential problems using callbacks
1. Untidy code: too many levels of nesting 2. Complex and error-prone
2. Promises
1. Object representing the eventual success or failure of an asynchronous action
2. Two parameters: resolve and reject (for which you write callbacks!)
The constructor syntax for a promise object is:
resolve and reject are callbacks provided by JavaScript
Asynchronous function (including body) is called the executor produces the results when it executes
a promise has three possible states:
Promise object is returned
Use then method to get the result of a promise
Handle error
Promise chains
Promise chains: feed the result of one promise to another Promise all: you can use this to resolve multiple promises
// prevent out-of-sequence using a Promise chain
console.log(// prevent out-of-sequence using a Promise chain) const one = () => {console.log(one)}
const two = () => {
return new Promise( (resolve, reject) => { setTimeout( () => {resolve(two)}, 2000)
const three = () => {
return new Promise( (resolve, reject) => {
setTimeout( () => {resolve(three)}, 2000) })
const four = () => {console.log(four)}
//now run our statements in the right sequence
two().then( (result2) => {
console.log(result2)
return three() }).then( (result3) => {
console.log(result3)
3. Async/Await
This is new to JS (2017) and is becoming popular in a number of programming languages.
Allows us to code as if program was synchronous.
Write async before function definition.
Write await to pause execution until the promise is resolved.
// prevent out-of-sequence using a Promise
console.log(// prevent out-of-sequence using a Promise)
const one = () => {console.log(one)}
const two = () => {
return new Promise( (resolve, reject) => {
setTimeout( () => {resolve(two)}, 3000) })
const three = () => {console.log(three)}
// now run our statements in the right sequence
two().then( (data) => {
console.log(data) three()
}).catch( (reason) => {
console.log(promise was rejected due to , reason) })
// prevent out-of-sequence using Async/Await
console.log(// prevent out-of-sequence using Async/Await) const one = () => {console.log(one)}
const two = () => {
return new Promise( (resolve, reject) => { setTimeout( () => {resolve(two)}, 2000)
const three = () => {console.log(three)}
// now run our statements in the right sequence
async function sequence() { one()
data = await two()
console.log(data)
} sequence()
Async/Await
We make no changes to our server api simulation.
async before function definition await to pause execution
Controller function from our Library App (next workshop)
On to databases
Next week well use asynchronous functions to connect our web app to databases.
web server sends request to database server
eventually, it returns with either data or an error
only then can we process the data (e.g. to render a template)
calls to MongoDB via Mongoose return a Promise
our apps can use either Promise or Async/Await syntax
CS: assignmentchef QQ: 1823890830 Email: [email protected]
Reviews
There are no reviews yet.