高仿race
var b = new Promise((reslove, reject) => {
setTimeout(() => {
reslove(1232)
}, 3000)
})
Promise.krace = function (org) {
return new Promise((resolve, reject) => {
org.forEach((item, index) => {
Promise.resolve(item).then(res => {
resolve(res)
})
});
})
}
Promise.krace([a, b]).then(res => {
console.log(res, '--res--')
})
高仿all
Promise.kall = function (org) {
let arr = []
let count = 0;
return new Promise((resolve, reject) => {
org.forEach((item, i) => {
Promise.resolve(item).then(res => {
arr[i] = res
count++;
if (count == org.length) resolve(arr)
})
});
})
}
Promise.kall([a, b]).then(res => {
console.log(res, '----res---')
})
高仿promise
class kPromise {
status = 'PADDING'
result = null;
Arrays = []
constructor(obj) {
obj(this.resolve.bind(this), this.reject.bind(this))
}
resolve(item) {
this.status = 'SUCCESS'
this.result = item;
this.Arrays.forEach((one, ind) => {
one['succ'](this.result)
})
}
reject(item) {
this.status = 'FAILED';
this.result = item;
this.Arrays.forEach((one, ind) => {
if (!one.full) throw Error('没有写这个reject函数');
one['full'](this.result)
})
}
then(onsucc, onfulled) {
return new Promise((reslove, reject) => {
if (this.status == 'PADDING') {
let obj = {
'succ': (one) => {
onsucc(one);
reslove(one)
}
}
onfulled ? obj.full = (one) => {
onsucc(one);
reslove(one)
} : null;
this.Arrays.push(obj)
}
if (this.status == 'SUCCESS') {
onsucc(this.result)
}
if (this.status == 'FAILED') {
onfulled(this.result)
}
})
}
}
new kPromise((resolve, reject) => {
setTimeout(() => {
reject(12321)
}, 3000)
}).then(res => {
console.log(res,'---reject--')
},(req)=>{
console.log(req,'----req--')
})
.then(res => {
console.log(res, '---')
})