1.Promise用法
function silentLogin(){ return new Promise(async (resolve,reject) => { let res = await apiLogin({'data':totalData.resdatapost,}) if(res.code ==200){ resolve(res.data); }else{ reject(res.data); } })}silentLogin().then(res =>{}).catch(err =>{})
2.手写Promise
function MyPromise(executor) { this.status = 'padding' // 定义初始状态 this.value = undefined // 定义初始值 this.onResolvedCallbacks = [] // 存放成功的回调 this.onRejectedCallbacks= [] // 存放失败的回调 let resolve = (value) => { if (this.status === 'padding') { this.status = 'resolve' this.value = value // 依次将对应的函数执行 this.onResolvedCallbacks.forEach(fn=>fn()); } } let reject = (value) =>{ if (this.status === 'padding') { this.status = 'reject' this.value = value // 依次将对应的函数执行 this.onRejectedCallbacks.forEach(fn=>fn()); } } try { executor(resolve, reject) } catch (reason) { reject(reason); } } // 定义 then 方法 MyPromise.prototype.then = function(onResolve, onReject) { switch(this.status){ case 'padding': //如果promise的状态是 pending,需要将 onFulfilled 和 onRejected 函数存放起来, //等待状态确定后,再依次将对应的函数执行 this.onResolvedCallbacks.push(() => { onResolve(this.value) }); this.onRejectedCallbacks.push(() => { onReject(this.value) }); break; case 'resolve' : onResolve(this.value) break; case 'reject': onReject(this.value) break; default: } } //测试 new MyPromise((resolve, reject) => { setTimeout(() => { resolve('成功') },1500) }) .then(res => { console.log('res',res) }, err => { console.log('err',err) })
3.Promise.all用法
Promise.all([p3,p1,p2]).then(res =>{ console.log(444,res) })
4.手写Promise.all
function myPromiseAll(promises){ return new Promise((resolve,reject) => { if(!Array.isArray(promises)){ throw new TypeError("promises must be an array but it resolved to " + typeof(promises)) } let result = [] let count = 0 promises.forEach((item,index) => { item.then((res) =>{ result[index] = res count++ if(count === promises.length){ resolve(result) } }, (err) =>{ reject(err) } ) }) }) }
// 测试Promise.All const p1 = new Promise((reslove,reject)=>{ setTimeout(function(){ reslove(1) },1000) }) const p2 = new Promise((reslove,reject)=>{ setTimeout(function(){ reslove(2) },2000) }) const p3 = new Promise((reslove,reject)=>{ setTimeout(function(){ reslove(3) },3000) }) myPromiseAll([p3,p1,p2]).then(res=>{ console.log(res) //[3,1,2] })