promise简易版

class Promises {
constructor( cb) {
this. thenArr = []; //存放then函数里面的成功的函数和失败的函数
this. cb = cb; //promise中的回调函数
this. count = 0; //计数
this. returnText = null; //返回值
this. resolve = this. resolve. bind( this);
this. reject = this. reject. bind( this);
this. cb( this. resolve, this. reject);
}

static all( promiseData) {
let resultData = [];
let errData = [];
return new Promises(( res, rej) => {
promiseData. forEach( i => {
i. then( data => {
resultData. push( data);
test();
}, ( err) => {
errData. push( err);
testerr();
})
})

function test() {
if ( promiseData. length === resultData. length) {
res( resultData)
}
}
 
function testerr() {
if ( errData. length > 0) {
rej( errData[ 0])
}
}
})
}

static race( promiseData) {
let resultData = [];
let errData = [];
return new Promises(( res, rej) => {
promiseData. forEach( i => {
i. then( data => {
resultData. push( data);
test();
}, ( err) => {
errData. push( err);
testerr();
})
})

function test() {
if ( promiseData. length > resultData. length) {
res( resultData)
}
}

function testerr() {
if ( errData. length === errData. length) {
rej( errData[ 0])
}
}
})
}
resolve( data) {
// 判断返回值的状态
// 1.返回值是promise
//2.返回值是普通的
let rest = this. thenArr. slice( this. count)
if ( this. returnText && this. returnText instanceof Promises) {
rest. forEach( item => {
this. returnText. then( item. okCb, item. errCn);
})
return;
} else if( this. returnText) {
this. thenArr[ this. count]. okCb( this. returnText);
} else {
this. returnText = this. thenArr[ this. count]. okCb( data);
}
this. count++;
if ( this. count < this. thenArr. length) {
this. resolve( data);
}
}
reject( err){
//如果失败,根据count执行当前then函数的失败函数
this. thenArr[ this. count]. errCn( err)
//如果失败的then函数下面还有未执行的then函数,则直接调用下一个then函数的成功函数
this. count++
if( this. count< this. thenArr. length){
this. resolve()
}
}
then( okCb, errCn) {
this. thenArr. push({
okCb,
errCn
})
return this;
}
}



let pro1=() =>{
return new Promises(( resolve, reject) =>{
setTimeout(() =>{
reject( 1)
}, 1000)
})
}

let pro2=() =>{
return new Promises(( resolve, reject) =>{
setTimeout(() =>{
reject( 2)
}, 2000)
})
}

Promises. race([ pro1(), pro2()]). then(( data) =>{
console. log( data)
},( err) =>{
console. log( err+ "2344")
})


// new Promises((res, rej) => {
// setTimeout(() => {
// rej(123)
// }, 1000)
// }).then((data) => {
// console.log(data)
// }, (err) => {
// console.log('err', err)
// }).then((data) => {
// return new Promise((res, rej) => {
// res(456)
// })
// }).then((data) => {
// console.log(data)
// })

猜你喜欢

转载自www.cnblogs.com/110162-wsx/p/10860780.html