🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Full Transcript

CP476A Internet Computing Week 9 – 1 – Async-2 Shaun Gao, Ph.D., P.Eng. Objectives Introduction JavaScript Asynchronous Promise concept states Promise instance methods then, catch, finally, Promise static methods all, any, race Difference between instance method and static method Introduction Synchr...

CP476A Internet Computing Week 9 – 1 – Async-2 Shaun Gao, Ph.D., P.Eng. Objectives Introduction JavaScript Asynchronous Promise concept states Promise instance methods then, catch, finally, Promise static methods all, any, race Difference between instance method and static method Introduction Synchronous in JavaScript Synchronous means to be in a sequence such that every statement of the code is executed one by one. So, basically a statement has to wait for the earlier statement to complete. Asynchronous in JavaScript Asynchronous means to allow the program to be executed immediately without waiting for the earlier statement to complete. Introduction – cont. Callback functions can achieve asynchronous functionality However, callback weakness, callback hell Promises A promise is a JavaScript object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. A Promise likes a proxy. It allows you to associate handlers with an asynchronous action's event: success or failure reason. A promise is a special JavaScript object that links the “producing code” and the “consuming code” together. Promise states The state of a promise is in one of the following states. fulfilled: Action related to the promise succeeded rejected: Action related to the promise failed pending: initial state. A promise cannot go from the fulfilled state to the rejected state and vice versa. Also, it cannot go back from the fulfilled or rejected state to the pending state. Promise benefits The benefits of using promises in JavaScript. Improves Code Readability. Better handling of asynchronous operations. Better flow of control definition in asynchronous logic. Better Error Handling. Avoid callback hell. Better performance Promise syntax Promise constructor takes only one argument which is a callback function Callback function takes two arguments, resolve and reject Perform operations inside the callback function and if everything went well then call resolve. Otherwise, it calls reject. If desired operations do not go well then reject is called. Promise example Example: function myDisplayer(some) { console.log(some); } let myPromise = new Promise(function(myResolve, myReject) { let x = 0; // The producing code if (x == 0) { myResolve("OK"); } else { myReject("Error"); } }); myPromise.then( // the consumer code function(value) {myDisplayer(value);}, function(error) {myDisplayer(error);} ); Demo01 Promise instance methods then() method is invoked when a promise is either resolved or rejected. Syntax: promise.then(onFulfilled, onRejected) then() method takes two functions as parameters. First function is executed if promise is resolved, and a result is received. Second function is executed if promise is rejected, and an error is received. Refer to demo01 for reference Promise instance methods – cont. catch() method deals with rejected cases only. Syntax: promise.catch(onRejected) onRejected is a function that is called when the promise is rejected. (Note: calling obj.catch(onRejected) is identical to calling obj.then(undefined, onRejected)) Example let promise = new Promise((resolve, reject) => { setTimeout(() => reject(new Error("Whoops!")), 1000); }); promise.catch(error => console.log(error)); Demo02 Question: JS has try{ … }catch(…){ … }, why do we need another catch here? Promise instance methods – cont. finally() method is called when the promise is finally either fulfilled or rejected. Finally() syntax promise.Finally(onFinally); onFinally is a function that is called when the Promise is settled. Example: Demo03 Demo03-01 Promise static methods Promise.all(iterable) Wait for all promises to be resolved, or for any to be rejected. Syntax: Promise.all(iterable); //iterable is an array Example Demo04 Demo04-1 Promise static methods – cont. Promise.any(iterable) Method any() takes an iterable of Promise objects and, as soon as one of the promises in the iterable fulfills, it returns a single promise that resolves with the value from that promise. Syntax: Promise.any(iterable); // iterable is an array Example Demo05 Promise static methods Promise.race(iterable) Method race() wait until any of the promises is fulfilled or rejected. Syntax: Promise.race(iterable); //iterable is an array Example Demo06 Demo06-1 Instance methods vs. static methods Static method: In JavaScript, a static method (or static function) is a method defined as a member of an object but is accessible directly from the object, rather than from an object instance created via the constructor. Instance method: In JavaScript, an instance method (or instance function) is a method that is defined from an object instance created via the contractor of an object. Refer to demo 01, 02, 03 for instance methods Refer to demo04, 05, 06 for static methods Instance methods vs. static methods – cont. Summary JavaScript Asynchronous Promise concept states Promise instance methods then, catch, finally, Promise static methods all, any, race Difference between instance method and static method Announcement Group project progress, Group project progress Project report due date: Mar. 25 Test 2 (cover week 5-8) next week (Mar 15) at 1:30 pm Bring your laptop CP476A Internet Computing Week 9– 2 Node.js modules Shaun Gao, Ph.D., P.Eng. Agenda Node.js modules Introduction Node.js modules Buffer module http module File system module URL module Crypto module DNS module Node.js events Timer module NPM Node.js - introduction Node.js is an open source server environment. Built on Chrome’s V8 JavaScript engine in 2008 Node.js allows you to run JavaScript on web server. Node.js uses asynchronous programming! Use event-driven technique What Can Node.js Do? Node.js can generate dynamic page content Node.js can create, open, read, write, delete, and close files on the server Node.js can collect form data Node.js can add, delete, modify data in your database Node.js – introduction – cont. Node.js features: Asynchronous architecture Concurrency control: Use queues instead of using mutexes Use callback instead of using multi-threads Question? Node.js versions Long-term support version: it is suitable for applications in production Current version: it is suitable for working with the newest features Node.js – introduction – cont. Download and install node.js from https://nodejs.org Command line interface Run JavaScript from command line >node JavaScriptFileName.js Display result using console.log() function console.log('The result is displayed in the Command Line Interface'); Node.js REPL environment REPL stands for Read, Evaluate, Print, Loop Allows the user to enter a JavaScript command, evaluate it, print the results, and loop to enter another command Supports multiline commands, customize command prompt and preconfigured context Sessions can be saved, and reloaded again Useful for learning JavaScript or executing tasks from a JavaScript command line Node.js - modules Node.js has a set of build-in modules How to include a module Use the keyword require example: var crypto = require('crypto’); How to use build-in modules, i.g. node.js (Buffer module) var buf = Buffer.from(‘xyz’); //Convert a string into binary data – ascii value console.log(buf); var buf1 = Buffer.from('abcdefghijkl'); var buf2 = Buffer.from('HELLO'); buf2.copy(buf1, 2); console.log(buf1.toString()); Demo01 Node.js – HTTP/HTTPS module HTTP Module, allows Node.js to transfer data over HTTP protocol var http = require('http’); //require(‘https’) Node.js becomes a web server by using HTTP module http.createServer(function (req, res) { res.write('Hello World!'); //write a response to the client res.end(); //end the response }).listen(8080); //the server object listens on port 8080 Demo02 – open one of your browser and type http://127.0.0.1:8080 or http://localhost:8080 Read user’s input, the Query String res.write(req.url); If the input is http://127.0.0.1:8080/summer, then the output will be /summer Demo03 Node.js – file system module Node.js file system module allows you to work with the file system var fs = require('fs’); The File System module can do the following. Read files Create files Update files Delete files Rename files Demo04 – read a file Node.js URL Module URL module splits up a web address into readable parts. var url = require('url’); Use url.parse() method to return a URL object with each part. var url = require('url'); var adr = 'http://localhost:8080/default.htm?year=2017&month=february'; var q = url.parse(adr, true); console.log(q.host); //returns 'localhost:8080' console.log(q.pathname); //returns '/default.htm' console.log(q.search); //returns '?year=2017&month=february’ Demo05 Node.js – File/web Server Create two html files and save them in the same folder (current working folder). var http = require('http’); var url = require('url’); var fs = require('fs’); http.createServer(function (req, res) { var q = url.parse(req.url, true); var filename = "." + q.pathname; //  “.” means current folder fs.readFile(filename, function(err, data) { if (err) { res.writeHead(404, {'Content-Type': 'text/html'}); return res.end("404 Not Found"); } res.writeHead(200, {'Content-Type': 'text/html'}); res.write(data); return res.end(); }); }). listen(8080); Demo06 Node.js – Crypto module Node.js contains OpenSSL, you can encrypt and decrypt any data Example: var crypto = require('crypto’); var Ekey = crypto.Cipher('aes-128-cbc’, ‘ '); var cipherT = Ekey.update(‘It is secret', 'utf8', 'hex') cipherT += Ekey.final('hex'); console.log(cipherT); var Dkey = crypto.Decipher('aes-128-cbc', ' '); var plainT = Dkey.update(cipherT, 'hex', 'utf8') plainT += Dkey.final('utf8'); console.log(plainT); Demo07 Node.js – DNS module DNS is domain name system that converts URL to IP address Example: var dns = require('dns'); var w3 = dns.lookup('www.wlu.ca', function (err, addresses, family) { console.log(addresses); }); //convert an IP to URL dns.reverse('216.249.48.130', (err, url) => console.log(url)); Demo08 Node.js – events module With events module, you can create-, fire-, and listen for- your own events. To include the built-in Events module use the require() method to access event properties and methods, create an EventEmitter object var events = require('events’); var eventEmitter = new events.EventEmitter(); To fire an event, use the emit() method. Demo09 Node.js – timer module The timers module contains functions that can execute code after a certain period of time. Timers module is mainly categorized into two categories Example: var myInt = setInterval(function () { // write Hello every 1 second console.log("Hello"); }, 1000); Demo10 Node.js - NPM NPM stands for Node.js package manager. NPM is the default package manager for the JavaScript runtime environment Node.js. It consists of a command line client and an online database of public and paid-for private packages, called the npm registry. NPM is included as a recommended feature in the Node.js installer. NPM is the world's largest Software Registry. Open-source developers use NPM to share software. Install new software with NPM. Summary Node.js modules Buffer module http module File system module URL module Crypto module DNS module Node.js events Timer module NPM Announcement Group project progress Project report due date: Mar. 25 Project report – The first page Software system design document Technical report Test 2 (cover week 5-8) next week (Mar 15) at 1:30 pm Bring your laptop

Use Quizgecko on...
Browser
Browser