Promise() 链式调用,可以支持多个并发请求,获取并发请求中的数据.
Promise可以解决异步的嵌套请求问题
resolve成功 reject失败 pending等待态
一旦promise成功了就不能失败了,相反也是一样
let p= new Promise((resolve,reject)=>{
console.log('1');
resolve('resolve'); 执行resolve或者reject,不会同时执行
reject('reject');
})
console.log('2');
p.then((value)=>{
console.log(value,'成功的原因');
},(err)=>{
console.log('err,promise中有错误');
});
1.如果then中返回一个普通值,那么会走下一个then成功回调,如果出错,走下一个then的错误回调
2.一个promise可以then多次
3.Promise.all([req1(),req2()]),返回一个新的promise
Promise.all([req1(),req2()]).then(([r1,r2])=>{},(error)=>{console.log(err)});
有一个失败,返回失败,全部成功,才成功
4.Promise.race([]) 返回最快的
5.Promise.resolve();返回一个成功promise
6.Promise.reject();返回失败promise
class Promise{
constructor(executor){
this.status='pending'
this.value=undefined
this.reason=undefined
}
function resolve(value){
if(this.status==='pending'){
this.status='resolved'
this.value=value;
}
}
function reject =reason =>{
if(this.status==='pending'){
this.status='rejected';
this.reason=reason
}
}
try {
executor(resolve,reject);
}catch(e){
reject(e)
}
then(onFufilled,onRejected){
if(this.status==='resolved'){
onFullfiled(this.value);
}
if(this.status==='rejected'){
onRejected(this.reason)
}
}
}
module.exports=Promise;
高阶函数:(函数返回函数)
function isType(type){
return function (content){
let t=Object.prototype.toString.call(content).replace(/\[object\s|\]/g,'');
return t===type;
}
}
let arr=['String','Number','Array']
arr.forEach((item)=>{
util['is'+item]=isType(item);
});
console.log(util.isString('123'));
高阶函数:传递callback