javascript async code: callback function、Eventlistener、 Promise、Generator、async/await
JS handle async code: callback function、Eventlistener、 Promise、Generator、async/await。
callback-----------
1.ajax;
2.setTimeout;
3.Eventlistener;
4.Nodejs method;
Promise-------------
Promise 1 way
function read(url){
return new Promise((resolve,reject)=>{
fs.readFile(url, 'utf8',
(err,data)=>{
if(err) reject(err);
resolve(data);
});
});
}
read(A).then(data=>{return read(B);})
.then(data=>{return read(C);})
.then(data=>{return read(D);})
.catch(reason=>{console.log(reason);});
//Promis.all----------
Promise.all([read(A),read(B),read(C)])
.then(data=>{console.log(data);})
.catch(err=>console.log(err)
);
Generator----------------------yield--------------
function* gen(){
let a=yield 111;
console.log(a);
let b=yield 222;
console.log(b);
let c=yield 333;
console.log(c);
let d=yield 444;
console.log(d);
}
let t=gen();
t.next(1); // first call next() function, parameter invalid, so no print;
t.next(2); // a output 2;
t.next(3); // b output 3;
t.next(4); // c output 4;
t.next(5); // d output 5;
async------------------------------------------------------
async is Generator function's short showing.
function testWait(){
return new Promise({resolve,reject}=>{
setTimeout(function(){
console.log("testWait");
resolve();
});
})
}
async function testAwaitUse(){
await testWait()
console.log("hello");
return 123;
// orderly out: testWait, hello
// If remove await from await testWait(), out: hello, testWait
}
console.log(testAwaitUse());
Promise--Object---Status---
Status: pending->fulfilled-> rejected;
Promise.prototype.then() and Promise.prototype.catch() will return a Promise.
const p1 = new Promise((resolve,reject)=>{});
Start---> p1().then()--->PENDING--> resolve: FULFILLED or reject: REJECTED;
callback() bind late, return value through, error pop;
/watch?v=kYaFS9AdoL4&list=PLHpfx416EzLPcj1JItKYftQDv8ghtoiXQ&index=16
2:09:20
all,allSettled,any, race------------------------
Promise.all(iterable)-----iterable: Array
function getBarList(){
return new Promise((resolve,reject)=>{
setTimeout(function(){resolve('bars')},300)
})
}
//
function getStoreList(){
return new Promise((resolve,reject)=>{
setTimeout(function(){resolve('stores')},500)
})
}
// function getProList(){
return new Promise((resolve,reject)=>{
setTimeout(function(){resolve('Pros')},700)
})
}
function initLoad(){
Promise.all([getBarList(),getStoreList(),getProList()])
.then(res=>{console.log(res)})
.catch(err=>{console.log(err)})
}
initLoad();
allSettled----------------------------
const resolved=Promise.resolve(2);
const rejected=Promise.reject(-1);
const allSettledPromise=Promise.allSettled([resolved, rejected]);
allSettledPromise.then(function(results){ console.log(results);});
//output
//[
// {status:'fulfilled',value:2},{status:'rejected',value:-1}
//]
Promise.any(iterable)------------------------------
return values has any fulfilled Promise, then return is fulfilled. all must be rejected, then return is rejected.
const resolved=Promise.resolve(2);
const rejected=Promise.reject(-1);
const allAnyPromise=Promise.any([resolved, rejected]);
allAnyPromise.then(function(results){ console.log(results);});
//output
// 2
Promise.race(iterable)------------------------------
function reqImg(){
var p=new Promise(function(resolve,reject){
var img = new Image();
img.onload = function(){resolve(img);}
img.src='www.xxx.com/a.png';
});
return p;
}
//lazy load
function timeout(){
var p = new Promise(function(resolve,reject){
setTimeout(function(){reject('over time');},5000);
});
}
Promise.race([reqImg(),timeout()])
.then(function(results){ console.log(results);})
.catch(function(results){console.log(results);});
all, all ok, then return;
allSettled, all done, then return sets;
any, any fulfilled, then return fulfilled; all rejected, then rejected;
race, first return fulfilled, then return it.
-----------------------------------------------------------------------
Data Type
1.Undefind
2.Null
3.Boolean
4.String
5.Number
6.BigInt
7.Symbol
8.Object(8.1Array,8.2Date,8.3Match,8.4Function,8.5RegExp)
funtion getType(obj){let t=typeof obj;if(t!=='object'){return t;}
return Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/, '$1');
}
Object.prototype.toString.call(window)//[object Window]
Object.prototype.toString.call(windows)//ReferenceError: windows is not defined
Object.prototype.toString.call(undefined)//[object Undefined]
Object.prototype.toString.call(1)//[object Number]
Object.prototype.toString.call(true)//[object Boolean]
Object.prototype.toString.call(null)//[object Null]
Object.prototype.toString.call('')//[object String]
let Car = function(){}
let m=new Car();
m instanceof Car //true
let s1=new String("StringObject");
s1 instanceof String //true
let s2='BaseString';
s2 instanceof String //false
function myInstanceof(left,right){if(typeof left!=='object' || left===null) return false;
let proto=Object.getPrototypeOf(left);
while(true){
if(proto===null) return false;
if(proto===right.prototype) return true;
proto=Object.getPrototypeof(proto);
}
}
callback-----------
1.ajax;
2.setTimeout;
3.Eventlistener;
4.Nodejs method;
Promise-------------
Promise 1 way
function read(url){
return new Promise((resolve,reject)=>{
fs.readFile(url, 'utf8',
(err,data)=>{
if(err) reject(err);
resolve(data);
});
});
}
read(A).then(data=>{return read(B);})
.then(data=>{return read(C);})
.then(data=>{return read(D);})
.catch(reason=>{console.log(reason);});
//Promis.all----------
Promise.all([read(A),read(B),read(C)])
.then(data=>{console.log(data);})
.catch(err=>console.log(err)
);
Generator----------------------yield--------------
function* gen(){
let a=yield 111;
console.log(a);
let b=yield 222;
console.log(b);
let c=yield 333;
console.log(c);
let d=yield 444;
console.log(d);
}
let t=gen();
t.next(1); // first call next() function, parameter invalid, so no print;
t.next(2); // a output 2;
t.next(3); // b output 3;
t.next(4); // c output 4;
t.next(5); // d output 5;
async------------------------------------------------------
async is Generator function's short showing.
function testWait(){
return new Promise({resolve,reject}=>{
setTimeout(function(){
console.log("testWait");
resolve();
});
})
}
async function testAwaitUse(){
await testWait()
console.log("hello");
return 123;
// orderly out: testWait, hello
// If remove await from await testWait(), out: hello, testWait
}
console.log(testAwaitUse());
Promise--Object---Status---
Status: pending->fulfilled-> rejected;
Promise.prototype.then() and Promise.prototype.catch() will return a Promise.
const p1 = new Promise((resolve,reject)=>{});
Start---> p1().then()--->PENDING--> resolve: FULFILLED or reject: REJECTED;
callback() bind late, return value through, error pop;
/watch?v=kYaFS9AdoL4&list=PLHpfx416EzLPcj1JItKYftQDv8ghtoiXQ&index=16
2:09:20
all,allSettled,any, race------------------------
Promise.all(iterable)-----iterable: Array
function getBarList(){
return new Promise((resolve,reject)=>{
setTimeout(function(){resolve('bars')},300)
})
}
//
function getStoreList(){
return new Promise((resolve,reject)=>{
setTimeout(function(){resolve('stores')},500)
})
}
// function getProList(){
return new Promise((resolve,reject)=>{
setTimeout(function(){resolve('Pros')},700)
})
}
function initLoad(){
Promise.all([getBarList(),getStoreList(),getProList()])
.then(res=>{console.log(res)})
.catch(err=>{console.log(err)})
}
initLoad();
allSettled----------------------------
const resolved=Promise.resolve(2);
const rejected=Promise.reject(-1);
const allSettledPromise=Promise.allSettled([resolved, rejected]);
allSettledPromise.then(function(results){ console.log(results);});
//output
//[
// {status:'fulfilled',value:2},{status:'rejected',value:-1}
//]
Promise.any(iterable)------------------------------
return values has any fulfilled Promise, then return is fulfilled. all must be rejected, then return is rejected.
const resolved=Promise.resolve(2);
const rejected=Promise.reject(-1);
const allAnyPromise=Promise.any([resolved, rejected]);
allAnyPromise.then(function(results){ console.log(results);});
//output
// 2
Promise.race(iterable)------------------------------
function reqImg(){
var p=new Promise(function(resolve,reject){
var img = new Image();
img.onload = function(){resolve(img);}
img.src='www.xxx.com/a.png';
});
return p;
}
//lazy load
function timeout(){
var p = new Promise(function(resolve,reject){
setTimeout(function(){reject('over time');},5000);
});
}
Promise.race([reqImg(),timeout()])
.then(function(results){ console.log(results);})
.catch(function(results){console.log(results);});
all, all ok, then return;
allSettled, all done, then return sets;
any, any fulfilled, then return fulfilled; all rejected, then rejected;
race, first return fulfilled, then return it.
-----------------------------------------------------------------------
Data Type
1.Undefind
2.Null
3.Boolean
4.String
5.Number
6.BigInt
7.Symbol
8.Object(8.1Array,8.2Date,8.3Match,8.4Function,8.5RegExp)
funtion getType(obj){let t=typeof obj;if(t!=='object'){return t;}
return Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/, '$1');
}
Object.prototype.toString.call(window)//[object Window]
Object.prototype.toString.call(windows)//ReferenceError: windows is not defined
Object.prototype.toString.call(undefined)//[object Undefined]
Object.prototype.toString.call(1)//[object Number]
Object.prototype.toString.call(true)//[object Boolean]
Object.prototype.toString.call(null)//[object Null]
Object.prototype.toString.call('')//[object String]
let Car = function(){}
let m=new Car();
m instanceof Car //true
let s1=new String("StringObject");
s1 instanceof String //true
let s2='BaseString';
s2 instanceof String //false
function myInstanceof(left,right){if(typeof left!=='object' || left===null) return false;
let proto=Object.getPrototypeOf(left);
while(true){
if(proto===null) return false;
if(proto===right.prototype) return true;
proto=Object.getPrototypeof(proto);
}
}
评论
发表评论