build script convert all ts files to js and move it to ./dist folder
copyfiles is a tool to help you to move files to destination folder
npm install -D copyfiles
tsconfig.jsonfile in a directory indicates that the directory is the root of a TypeScript project. The tsconfig.json file specifies the root files and the compiler options required to compile the project.
so once you call tsc command it will build all files specified by tsconfig.json to target
let var1:string|number=44;
let var2:object={};
let var3:any;
let var4:void;//null or undefined
//===============================
let strArr:string[];//accept only array of string
let strArr2:[string,number];//tuple string,number
let strArr3:Array<string>;
//========================
let any:any;//take any value
let fun:(a: string) => void;//function type
TypeScript interface
interface Options {
color: string;
volume: number;
}
let options = {} as Options;
options.color = "red";
options.volume = 11;
interface User {
name: string;
id: number;
}
class UserAccount {
name: string;
id: number;
constructor(name: string, id: number) {
this.name = name;
this.id = id;
}
}
const user: User = new UserAccount("Murphy", 1);
interface IPerson {
name: string;
display():void;
}
interface IEmployee {
empCode: number;
}
class Employee implements IPerson, IEmployee {
empCode: number;
name: string;
constructor(empcode: number, name:string) {
this.empCode = empcode;
this.name = name;
}
display(): void {
console.log("Name = " + this.name + ", Employee Code = " + this.empCode);
}
}
let per:IPerson = new Employee(100, "Bill");
per.display(); // Name = Bill, Employee Code = 100
let emp:IEmployee = new Employee(100, "Bill");
emp.display(); //Compiler Error: Property 'display' does not exist on type 'IEmployee'
class Car {
name: string;
constructor(name: string) {
this.name = name;
}
run(speed:number = 0) {
console.log("A " + this.name + " is moving at " + speed + " mph!");
}
}
class Mercedes extends Car {
constructor(name: string) {
super(name);
}
run(speed = 150) {
console.log('A Mercedes started')
super.run(speed);
}
}
class Honda extends Car {
constructor(name: string) {
super(name);
}
run(speed = 100) {
console.log('A Honda started')
super.run(speed);
}
}
let mercObj = new Mercedes("Mercedes-Benz GLA");
let hondaObj = new Honda("Honda City")
mercObj.run(); // A Mercedes started A Mercedes-Benz GLA is moving at 150 mph!
hondaObj.run(); // A Honda started A Honda City is moving at 100 mph!
class StaticMem {
static num:number;
static disp():void {
console.log("The value of num is"+ StaticMem.num)
}
}
StaticMem.num = 12 // initialize the static variable
StaticMem.disp() // invoke the static method
abstract class Person {
abstract name: string;
display(): void{
console.log(this.name);
}
}
class Employee extends Person {
name: string;
empCode: number;
constructor(name: string, code: number) {
super(); // must call super()
this.empCode = code;
this.name = name;
}
}
let emp: Person = new Employee("James", 100);
emp.display(); //James
class StaticMem {
static num:number;
static disp():void {
console.log("The value of num is"+ StaticMem.num)
}
}
StaticMem.num = 12 // initialize the static variable
StaticMem.disp() // invoke the static method
const myCanvas = document.getElementById("main_canvas") as HTMLCanvasElement;
type aliases
type func=(a: string) => void;
type Point = {
x: number;
y: number;
};
// Exactly the same as the earlier example
function printCoord(pt: Point) {
console.log("The coordinate's x value is " + pt.x);
console.log("The coordinate's y value is " + pt.y);
}
printCoord({ x: 100, y: 100 });
Primary Key (Default key _id provided by MongoDB itself)
{
_id: ObjectId(7df78ad8902c)
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100,
comments: [
{
user:'user1',
message: 'My first comment',
dateCreated: new Date(2011,1,20,2,15),
like: 0
},
{
user:'user2',
message: 'My second comments',
dateCreated: new Date(2011,1,25,7,45),
like: 5
}
]
}
Embedded Data Model
In this model, you can have (embed) all the related data in a single document, it is also known as de-normalized data model.
For example, assume we are getting the details of employees in three different documents namely, Personal_details, Contact and, Address, you can embed all the three documents in a single one
In this model, you can refer the sub documents in the original document, using references. For example, you can re-write the above document in the normalized model as:
Builds the index in the background so that building an index does not block other database activities. Specify true to build in the background. The default value is false.
unique
Boolean
Creates a unique index so that the collection will not accept insertion of documents where the index key or keys match an existing value in the index. Specify true to create a unique index. The default value is false.
name
string
The name of the index. If unspecified, MongoDB generates an index name by concatenating the names of the indexed fields and the sort order.
sparse
Boolean
If true, the index only references documents with the specified field. These indexes use less space but behave differently in some situations (particularly sorts). The default value is false.
expireAfterSeconds
integer
Specifies a value, in seconds, as a TTL to control how long MongoDB retains documents in this collection.
weights
document
The weight is a number ranging from 1 to 99,999 and denotes the significance of the field relative to the other indexed fields in terms of the score.
default_language
string
For a text index, the language that determines the list of stop words and the rules for the stemmer and tokenizer. The default value is English.
language_override
string
For a text index, specify the name of the field in the document that contains, the language to override the default language. The default value is language.
Following are the possible stages in aggregation framework −
$project − Used to select some specific fields from a collection.
$match − This is a filtering operation and thus this can reduce the amount of documents that are given as input to the next stage.
$group − This does the actual aggregation as discussed above.
$sort − Sorts the documents.
$skip − With this, it is possible to skip forward in the list of documents for a given amount of documents.
$limit − This limits the amount of documents to look at, by the given number starting from the current positions.
$unwind − This is used to unwind document that are using arrays. When using an array, the data is kind of pre-joined and this operation will be undone with this to have individual documents again. Thus with this stage we will increase the amount of documents for the next stage.
Expression
Description
Example
$sum
Sums up the defined value from all documents in the collection.
Gets the first document from the source documents according to the grouping. Typically this makes only sense together with some previously applied “$sort”-stage.
Gets the last document from the source documents according to the grouping. Typically this makes only sense together with some previously applied “$sort”-stage.
Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. It facilitates the rapid development of Node based Web applications. Following are some of the core features of Express framework −
Allows to set up middlewares to respond to HTTP Requests.
Defines a routing table which is used to perform different actions based on HTTP Method and URL.
Allows to dynamically render HTML Pages based on passing arguments to templates.
Installing Express
Firstly, install the Express framework globally using NPM so that it can be used to create a web application using node terminal.
$ npm install express --save
The above command saves the installation locally in the node_modules directory and creates a directory express inside node_modules. You should install the following important modules along with express −
body-parser − This is a node.js middleware for handling JSON, Raw, Text and URL encoded form data.
cookie-parser − Parse Cookie header and populate req.cookies with an object keyed by the cookie names.
multer − This is a node.js middleware for handling multipart/form-data.
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World');
})
app.get(/a/, function (req, res) {//any url contains a
res.send('/a/')
})
app.get('/name/:name',function (req,res){//req.params={name:"mohammed"}
res.send("hello world");
});
var server = app.listen(8081, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port)
})
app.route('/book')
.get(function (req, res) {
res.send('Get a random book')
})
.post(function (req, res) {
res.send('Add a book')
})
.put(function (req, res) {
res.send('Update the book')
})
static files
Express provides a built-in middleware express.static to serve static files, such as images, CSS, JavaScript, etc. You simply need to pass the name of the directory where you keep your static assets, to the express.static middleware to start serving the files directly. For example, if you keep your images, CSS, and JavaScript files in a directory named public, you can do this −
var express = require('express')
var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
app.get('/', function(req, res) {
console.log("Cookies: ", req.cookies)
})
app.listen(8081)
middleware
app.get('/example/b', function (req, res, next) {
console.log('the response will be sent by the next function ...')
next()
}, function (req, res) {
res.send('Hello from B!')
})
var cb0 = function (req, res, next) {
console.log('CB0')
next()
}
var cb1 = function (req, res, next) {
console.log('CB1')
next()
}
var cb2 = function (req, res) {
res.send('Hello from C!')
}
app.get('/example/c', [cb0, cb1, cb2])//multiple response
let config=require("./config");
let express=require("express");
let app=express();
app.use(function(req,res,next){
console.log("middleware");
next();
});
app.get('/name',function (req,res){
res.send(req.query);
});
let server=app.listen(config.port,()=>{
console.log(server);
});
var express = require('express')
var router = express.Router()
// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
console.log('Time: ', Date.now())
next()
})
// define the home page route
router.get('/', function (req, res) {
res.send('Birds home page')
})
// define the about route
router.get('/about', function (req, res) {
res.send('About birds')
})
module.exports = router
Content-Type: application/json
app.use(express.json())
Content-Type: application/x-www-form-urlencoded
app.use(express.urlencoded({
extended: true
}))
and you can acess to it by
req.body.fieldName;
raw data
const express=require("express");
const bodyParser = require('body-parser');
let options = {
inflate: true,
limit: '100kb',
type: 'text/plain'
};
let app=express();
app.use(bodyParser.raw(options));
app.post("/hello",(req,res)=>{
res.send(req.body);//body is string if type: 'text/*' else buffer
})
app.listen(8081,()=>{});
The methods on the response object (res) in the following table can send a response to the client, and terminate the request-response cycle. If none of these methods are called from a route handler, the client request will be left hanging.
npm run start or npm start
npm run prod or npm prod
npm debug or npm run debug
Process Module
The process object is a global that provides information about, and control over, the current Node.js process. As a global, it is always available to Node.js applications without using require()
process.stderr.write("hello world");
process.stdin.on("data", (data) => {
const name = data.toString().trim().toUpperCase();
if (name !== "") {
process.stdout.write(`Hello ${name}!`);
} else {
process.stderr.write("Input was empty.");
}
});
process.on('exit', function () {
fs.writeFileSync('/tmp/myfile', 'This MUST be saved on exit.');
});
process.on('uncaughtException', function (err) {
console.error('An uncaught error occurred!');
console.error(err.stack);
});
The default behavior on uncaughtException is to print a stack trace and exit – using the above, your program will display the message provided and the stack trace, but will not exit.
There are also a variety of methods attached to the process object, many of which deal with quite advanced aspects of a program. We’ll take a look at a few of the more commonly useful ones, while leaving the more advanced parts for another article.
process.exit exits the process. If you call an asynchronous function and then call process.exit() immediately afterwards, you will be in a race condition – the asynchronous call may or may not complete before the process is exited. process.exit accepts one optional argument – an integer exit code. 0, by convention, is an exit with no errors.
process.cwd returns the ‘current working directory’ of the process – this is often the directory from which the command to start the process was issued.
process.chdir is used to change the current working directory. For example:
setTimeout(function () {
// code here
}, 0)
process.nextTick(function () {//prefer this
console.log('Next trip around the event loop, wheeee!')
});
The process.argv property returns an array containing the command-line arguments passed when the Node.js process was launched.
Watching for file updates Node.js’s fs module provides functionality that enables you to watch files and track when files or directories are created, updated, or deleted. In this recipe, we’ll create a small program named watch.js that watches for changes in a file using the watchFile() API and then prints a message when a change has occurred.
const fs = require("fs");
const file = "./file.txt";
const moment = require("moment");
fs.watch(file, (eventType, filename) => {
const time = moment().format("MMMM Do YYYY, h:mm:ss a");
return console.log(`${filename} updated ${time}`);
});
Events
var events = require('events');
let emitter=new events.EventEmitter();
emitter.on("click",()=>{console.log("call 1")});
emitter.on("click",()=>{console.log("call 2")});
emitter.on("click",()=>{console.log("call 3")});
emitter.emit("click");//call 1 call 2 call 3
var events = require('events');
function fun1(){
console.log("fun1");
}
function fun2(){
console.log("fun2");
}
let emitter=new events.EventEmitter();
emitter.addListener("click",fun1);
emitter.addListener("click",fun2);
emitter.emit("click");//fun1,fun2
emitter.removeListener("click",fun1);
emitter.emit("click");//fun2
buffer
Pure JavaScript is Unicode friendly, but it is not so for binary data. While dealing with TCP streams or the file system, it’s necessary to handle octet streams. Node provides Buffer class which provides instances to store raw data similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap.Buffer class is a global class that can be accessed in an application without importing the buffer module.
var buf = new Buffer(10);
var buf = new Buffer([10, 20, 30, 40, 50]);
var buf = new Buffer("Simply Easy Learning", "utf-8");
buf = new Buffer(256);
len = buf.write("Simply Easy Learning");
console.log("Octets written : "+ len);//20
buf.toString([encoding][, start][, end])
Live Demo
buf = new Buffer(26);
for (var i = 0 ; i < 26 ; i++) {
buf[i] = i + 97;
}
console.log( buf.toString('ascii')); // outputs: abcdefghijklmnopqrstuvwxyz
console.log( buf.toString('ascii',0,5)); // outputs: abcde
console.log( buf.toString('utf8',0,5)); // outputs: abcde
console.log( buf.toString(undefined,0,5)); // encoding defaults to 'utf8', outputs abcde
var buffer1 = new Buffer('TutorialsPoint ');
var buffer2 = new Buffer('Simply Easy Learning');
var buffer3 = Buffer.concat([buffer1,buffer2]);
console.log("buffer3 content: " + buffer3.toString());
var buffer1 = new Buffer('ABC');
//copy a buffer
var buffer2 = new Buffer(3);
buffer1.copy(buffer2);
console.log("buffer2 content: " + buffer2.toString());
Live Demo
var buffer1 = new Buffer('TutorialsPoint');
//slicing a buffer
var buffer2 = buffer1.slice(0,9);
console.log("buffer2 content: " + buffer2.toString());
Streams
var fs = require("fs");
var data = '';
// Create a readable stream
var readerStream = fs.createReadStream('input.txt');
// Set the encoding to be utf8.
readerStream.setEncoding('UTF8');
// Handle stream events --> data, end, and error
readerStream.on('data', function(chunk) {
data += chunk;
});
readerStream.on('end',function() {
console.log(data);
});
readerStream.on('error', function(err) {
console.log(err.stack);
});
console.log("Program Ended");//call first
var fs = require("fs");
var data = 'Simply Easy Learning';
// Create a writable stream
var writerStream = fs.createWriteStream('output.txt');
// Write the data to stream with encoding to be utf8
writerStream.write(data,'UTF8');
// Mark the end of file
writerStream.end();
// Handle stream events --> finish, and error
writerStream.on('finish', function() {
console.log("Write completed.");
});
writerStream.on('error', function(err) {
console.log(err.stack);
});
console.log("Program Ended");
var fs = require("fs");
// Create a readable stream
var readerStream = fs.createReadStream('input.txt');
// Create a writable stream
var writerStream = fs.createWriteStream('output.txt');
// Pipe the read and write operations
// read input.txt and write data to output.txt
readerStream.pipe(writerStream);
console.log("Program Ended");
Variable hoisting allows the use of a variable in a JavaScript program, even before it is declared. Such variables will be initialized to undefined by default. JavaScript runtime will scan for variable declarations and put them to the top of the function or script. Variables declared with var keyword get hoisted to the top.
//hoisted to top ; var i = undefined
for (var i = 1;i <= 5;i++){
console.log(i);
}
console.log("after the loop i value is "+i);
//variable company is hoisted to top , var company = undefined
console.log(company); // using variable before declaring
var company = "TutorialsPoint"; // declare and initialized here
console.log(company);
var balance = 5000
console.log(typeof balance)//Number
var balance = {message:"hello"}
console.log(typeof balance)//Object
Operators
let a=null;
let b=a||12;//right hand if left hand is false b=12
let a=null;
let b=a&&12;//right hand if left hand is not false
?. and Nullish (??) operator
let m=undefined;
console.log(m?.hello)//undefined
let m=undefined??"mohammed";//right hand if left is null or undefined
console.log(m);//mohammed
Spread operator
<script>
function addThreeNumbers(a,b,c){
return a+b+c;
}
const arr = [10,20,30]
console.log('sum is :',addThreeNumbers(...arr))
console.log('sum is ',addThreeNumbers(...[1,2,3]))
</script>
//copy array using spread operator
let source_arr = [10,20,30]
let dest_arr = [...source_arr]
console.log(dest_arr)
//concatenate two arrays
let arr1 = [10,20,30]
let arr2 =[40,50,60]
let arr3 = [...arr1,...arr2]
console.log(arr3)
<script>
//copy object
let student1 ={firstName:'Mohtashim',company:'TutorialsPoint'}
let student2 ={...student1}
console.log(student2)
//concatenate objects
let student3 = {lastName:'Mohammad'}
let student4 = {...student1,...student3}
console.log(student4)
</script>
Loops
in loop
let a={a:"hello",b:"world"}
for(let m in a){
console.log(a[m]);
}
of loop
let a=[1,2,3,4];
for(let m of a){
console.log(m);
}
label with break
outerloop: // This is the label name
for (var i = 0; i < 5; i++) {
console.log("Outerloop: " + i);
innerloop:
for (var j = 0; j < 5; j++){
if (j > 3 ) break ; // Quit the innermost loop
if (i == 2) break innerloop; // Do the same thing
if (i == 4) break outerloop; // Quit the outer loop
console.log("Innerloop: " + j);
}
}
Functions
constructor function
function A(val){
this.b=val;
}
let a=new A(12);
console.log(a.b);//12
console.log(a instanceof A);//true
console.log(A.prototype===a.__proto__);//true
A.prototype.x=32;
console.log(a.x);//32
console.log(a.hasOwnProperty("x"));//false
a.x=321;
console.log(a.hasOwnProperty("x"));//true
function B(){
}
function A(val){
this.val=val;
}
A.prototype=new B();
A.prototype.val2=44;
let m=new A(12);
console.log(m instanceof A,m instanceof B);//true true
console.log(m.constructor);//B
Rest parameters
function fun1(...params) {
console.log(params.length);
}
fun1();
fun1(5);
fun1(5, 6, 7);
Lambda functions
var msg = ()=> {
console.log("function invoked")
}
msg()
var msg = x=> {
console.log(x)
}
msg(10)
Function Hoisting
Like variables, functions can also be hoisted. Unlike variables, function declarations when hoisted, hoists the function definition rather than just hoisting the function’s name.
hoist_function(); //call function
function hoist_function() {
console.log("foo");
}
hoist_function(); // TypeError: hoist_function() is not a function
var hoist_function() = function() {
console.log("bar");
};
Generator function
"use strict"
function* rainbow() {
// the asterisk marks this as a generator
yield 'red';
yield 'orange';
yield 'yellow';
yield 'green';
yield 'blue';
yield 'indigo';
yield 'violet';
}
for(let color of rainbow()) {
console.log(color);
}
function* ask() {
const name = yield "What is your name?";
const sport = yield "What is your favorite sport?";
return `${name}'s favorite sport is ${sport}`;
}
const it = ask();
console.log(it.next());
console.log(it.next('Ethan'));
console.log(it.next('Cricket'));
destructing parameters
fun1({A:"hello",B:"world"});
fun2(["hello","world"]);
function fun1({A,B}){
console.log(A,B);
}
function fun2([A,B]){
console.log(A,B);
}
bind and apply
function f(){
console.log(this.v);
console.log(arguments);
}
let ob={v:12};
f.bind(ob)();//12
f.apply(ob,["a","b","c"]);//12 [Arguments] { '0': 'a', '1': 'b', '2': 'c' }
Objects
let A={};
let B=A;
let C={};
C[A]=12;
console.log(C[B]);
let k=12;
let A={k};
console.log(A["k"]);
var myCar = new Object();
myCar.make = "Ford"; //define an object
myCar.model = "Mustang";
myCar.year = 1987;
console.log(myCar["make"]) //access the object property
console.log(myCar["model"])
console.log(myCar["year"])
let A={"v1":12};
let B=Object.create(A);
console.log(B.v1);//12
console.log(B===A);//false
delete property
// Creates a new object, myobj, with two properties, a and b.
var myobj = new Object;
myobj.a = 5;
myobj.b = 12;
// Removes the ‘a’ property
delete myobj.a;
console.log ("a" in myobj) // yields "false"
<script>
let student = {
rollno:20,
name:'Prijin',
cgpa:7.2
}
//destructuring to same property name
let {name,cgpa} = student
console.log(name)
console.log(cgpa)
//destructuring to different name
let {name:student_name,cgpa:student_cgpa}=student
console.log(student_cgpa)
console.log("student_name",student_name)
</script>
let customers= {
c1:101,
c2:102,
c3:103
}
let {c1,...others} = customers
console.log(c1)//c1
console.log(others)//c2,c3
let emp = {
id:101,
address:{
city:'Mumbai',
pin:1234
}
}
let {address} = emp;
console.log(address)
let {address:{city,pin}} = emp
console.log(city)//mumbai
define property
let B={a:1,b:2,c:3};
Object.defineProperty(B,"h",{ enumerable:true, value:4, configurable:true,writable:true});
for(let m in B){
console.log(m);//a,b,c,h all of them they are enumerable
}
B.h={A:32};//can write on value because it writable
delete B.h;//can delete because it configurable
console.log(B.h);
set and get
let B={a:1,b:2,c:3};
Object.defineProperty(B,"d",{ set(v) {console.log("hello");
},get() {console.log("world");
}});
B.d=345;//hello
let m=B.d;//world
let C={set name(v) {console.log("set ",v);
},get name() {
console.log("get");
}};
C.name=43;//set 43
function constructor(){
this.val=12;
}
let obj=new constructor();
obj.a=1;
obj.b=2;
console.log(Object.keys(obj));//[val,a,b]
?. and ?? operator
let m=undefined;
console.log(m?.hello)//undefined
let m=undefined??"mohammed";
console.log(m);//mohammed
Number
var num = new Number(10);
console.log(num.toString());
console.log(num.toString(2));//binary
console.log(num.toString(8));//octal
let val=41.2334
console.log(val.toFixed(1))//41.2
console.log(Number(" 12.453 "));//12.453
let val=Number("hello");
console.log(Number.isNaN(val));//true
let val=new Number(12);//instanceof Number
let val=12;//not instanceof Number
String
const str = "Please locate where 'locate' occurs!";
console.log(str.length);//36
console.log(str.indexOf("locate"));//7
console.log(str.toUpperCase());//PLEASE LOCATE WHERE 'LOCATE' OCCURS!
console.log(str.split(' '));//[ 'Please', 'locate', 'where', "'locate'", 'occurs!' ]
console.log(str.endsWith('!'));//true
console.log(str.substr(7))//locate where 'locate' occurs!
let str2=" I Like Frutes ";
str2=str2.trim();
console.log(str2.replace(/(\s+)/i,','));//I,Like Frutes
console.log(str2.search(/\w{0,2}\s/i));//0
console.log(str2.match(/(\w+\s*)/gi));//[ 'I ', 'Like ', 'Frutes' ]
var text1 = "Hello";
var text2 = "World";
var text3 = text1.concat(" ", text2);//Hello World
array.sort( compareFunction ); //or with no compare functions for numbers ands string array
push(element)//add to end
unshift(element)//add to first
shift()//remove first
pop()//remove last
let daysMap = new Map();
daysMap.set('1', 'Monday');
daysMap.set('2', 'Tuesday');
daysMap.set('3', 'Wednesday');
console.log(daysMap.size);
let andy = {ename:"Andrel"},
varun = {ename:"Varun"},
prijin = {ename:"Prijin"}
let empJobs = new Map([[andy,'Software Architect'],[varun,'Developer']]);
console.log(empJobs)//{{…} => "Software Architect", {…} => "Developer"}
'use strict'
var roles = new Map([
['r1', 'User'],
['r2', 'Guest'],
['r3', 'Admin'],
]);
for(let r of roles.entries())
console.log(`${r[0]}: ${r[1]}`);
let m=new Map([["ali",1],["mohammed",2]]);
for(let [k,v] of m.entries()){
console.log(k,v);
}
Promise
function add_positivenos_async(n1, n2) {
let p = new Promise(function (resolve, reject) {
if (n1 >= 0 && n2 >= 0) {
//do some complex time consuming work
resolve(n1 + n2)
}
else
reject('NOT_Postive_Number_Passed')
})
return p;
}
add_positivenos_async(10, 20)
.then(successHandler) // if promise resolved
.catch(errorHandler);// if promise rejected
add_positivenos_async(-10, -20)
.then(successHandler) // if promise resolved
.catch(errorHandler);// if promise rejected
function errorHandler(err) {
console.log('Handling error', err)
}
function successHandler(result) {
console.log('Handling success', result)
}
console.log('end')
function add_positivenos_async(n1, n2) {
let p = new Promise(function (resolve, reject) {
if (n1 >= 0 && n2 >= 0) {
//do some complex time consuming work
resolve(n1 + n2)
}
else
reject('NOT_Postive_Number_Passed')
})
return p;
}
add_positivenos_async(10,20)
.then(function(result){
console.log("first result",result)
return add_positivenos_async(result,result)
}).then(function(result){
console.log("second result",result)
return add_positivenos_async(result,result)
}).then(function(result){
console.log("third result",result)
})
console.log('end')
promise.all() This method can be useful for aggregating the results of multiple promises.
function add_positivenos_async(n1, n2) {
let p = new Promise(function (resolve, reject) {
if (n1 >= 0 && n2 >= 0) {
//do some complex time consuming work
resolve(n1 + n2)
}
else
reject('NOT_Postive_Number_Passed')
})
return p;
}
//Promise.all(iterable)
Promise.all([add_positivenos_async(10,20),add_positivenos_async(30,40),add_positivenos_async(50,60)])
.then(function(resolveValue){
console.log(resolveValue[0])
console.log(resolveValue[1])
console.log(resolveValue[2])
console.log('all add operations done')
})
.catch(function(err){
console.log('Error',err)
})
console.log('end')
/*
end
30
70
110
all add operations done
*/
promise.race() This function takes an array of promises and returns the first promise that is settled.
function add_positivenos_async(n1, n2) {
let p = new Promise(function (resolve, reject) {
if (n1 >= 0 && n2 >= 0) {
//do some complex time consuming work
resolve(n1 + n2)
} else
reject('NOT_Postive_Number_Passed')
})
return p;
}
//Promise.race(iterable)
Promise.race([add_positivenos_async(10,20),add_positivenos_async(30,40)])
.then(function(resolveValue){
console.log('one of them is done')
console.log(resolveValue)
}).catch(function(err){
console.log("Error",err)
})
console.log('end')
async
async function fun(){
return 100;
}
Promise.all([fun(),fun(),fun()]).then((res)=>{
console.log(res);});
await
async function fun(){
return 100;
}
async function fun2(){
let prom=Promise.all([fun(),fun(),fun()]);
let res=await prom;
return res;
}
fun2().then(res=>{console.log(res)});//[ 100, 100, 100 ]
async function f() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 1000)
});
let result = await promise; // wait until the promise resolves (*)
alert(result); // "done!"
}
f();
class
class A{
m=12;
constructor(val) {
console.log(val);
this.m=val;
}
set value(val){
this.m=val;
}
get value() {
return this.m;
}
}
let a=new A(12);//12
a.value=22;
console.log(a.value);//22
class A{
m=12;
constructor(val) {
console.log("A : ",val);
this.m=val;
}
set value(val){
this.m=val;
}
get value() {
return this.m;
}
}
class B extends A{
constructor(val) {
super(val);
console.log("B : ",val)
}
}
let b=new B(12);//A : 12 B : 12
class A{
#m=12;//private field
}
get constructor from object
class A{
}
let a=new A();
console.log(a.constructor==A);//true
call super members
class A{
constructor() {
}
fun(){
console.log("A");
}
}
class B extends A{
constructor() {
super();
}
fun(){
super.fun();
console.log("B");
}
}
let b=new B();
b.fun();//A B
export and import
// export an array
export let months = ['Jan', 'Feb', 'Mar','Apr', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
// export a constant
export const MODULES_BECAME_STANDARD_YEAR = 2015;
// export a class
export class User {
constructor(name) {
this.name = name;
}
}
export function sayHi(user) {
alert(`Hello, ${user}!`);
} // no ; at the end
// ? say.js
function sayHi(user) {
alert(`Hello, ${user}!`);
}
function sayBye(user) {
alert(`Bye, ${user}!`);
}
export {sayHi, sayBye}; // a list of exported variables
// ? main.js
import {sayHi, sayBye} from './say.js';
sayHi('John'); // Hello, John!
sayBye('John'); // Bye, John!
// ? main.js
import * as say from './say.js';
say.sayHi('John');
say.sayBye('John');
// ? main.js
import {sayHi as hi, sayBye as bye} from './say.js';
hi('John'); // Hello, John!
bye('John'); // Bye, John!
// ? say.js
...
export {sayHi as hi, sayBye as bye};
// ? main.js
import * as say from './say.js';
say.hi('John'); // Hello, John!
say.bye('John'); // Bye, John!
Export default
In practice, there are mainly two kinds of modules.
Modules that contain a library, pack of functions, like say.js above.
Modules that declare a single entity, e.g. a module user.js exports only class User.
Mostly, the second approach is preferred, so that every “thing” resides in its own module.
// ? user.js
export default class User { // just add "default"
constructor(name) {
this.name = name;
}
}
// ? main.js
import User from './user.js'; // not {User}, just User
new User('John');
function sayHi(user) {
alert(`Hello, ${user}!`);
}
// same as if we added "export default" before the function
export {sayHi as default};
// ? user.js
export default class User {
constructor(name) {
this.name = name;
}
}
export function sayHi(user) {
alert(`Hello, ${user}!`);
}
// ? main.js
import {default as User, sayHi} from './user.js';
new User('John');
// ? main.js
import * as user from './user.js';
let User = user.default; // the default export
new User('John');
re-export
export {sayHi} from './say.js'; // re-export sayHi
export {default as User} from './user.js'; // re-export default
export * from './user.js'; // to re-export named exports
export {default} from './user.js'; // to re-export the default export
operators
Operator_Name
Description
Example
in
It is used to check for the existence of a property on an object.
let Bike = {make: ‘Honda’, model: ‘CLIQ’, year: 2018}; console.log(‘make’ in Bike); // Output: true
delete
It is used to delete the properties from the objects.
class A{
}
let m:A;
//============================
type AA={
m:string
}
let mm:AA={m:"hello"};
//=================================
function fun(l:number,s:boolean):void{//can return null or undefined or nothing
return undefined;
}
function fun2(cb,a?:string){ //second parameter can be empty
}
fun2(()=>{});
//===============================
let strArr:string[];//accept only array of string
let strArr2:[string,number];//accept only array of strings and numbers
let strArr3:Array<string>;
//========================
let any:any;//take any value