Promise.prototype.myRace = function (target) {
let arr = Array.from(target);
return new Promise((resolve, reject) => {
for(let i=0; i<arr.length; i++){
if(typeof arr[i].then === 'function'){
arr[i].then(value => resolve(value), reject);
}else{
resolve(arr[i]);
}
}
})
}
Promise.prototype.myAll = function(target){
let arr = Array.from(target);
return new Promise((resolve, reject) => {
let result = [], count = 0;
const length = arr.length;
function getResult(val, index) {
result[index] = val;
count++;
if(count === length){
resolve(result);
}
}
for(let i=0; i<length; i++){
if(typeof arr[i].then === 'function'){
arr[i].then(val => getResult(val, i), reject);
}else{
getResult(arr[i], i);
}
}
})
}
Promise.prototype.myCatch = function(callBack){
return this.then(null, callBack);
}
Promise.prototype.myFinally = function(callBack){
return this.then(value => {
return Promise.resolve(callBack()).then(() => value);
}, err => {
return Promise.resolve(callBack()).then(() => err);
})
}
let p1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('123');
}, 1000)
})
let p2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('123');
}, 4000)
})
const PENDING = 'pending';
const RESOLVED = 'resolved';
const REJECTED = 'rejected';
class MyPromise{
constructor(exec) {
this.status = PENDING;
this.value = undefined;
this.reason = undefined;
this.resolvedCb = [];
this.rejectedCb = [];
let resolve = value => {
this.value = value;
this.status = RESOLVED;
this.resolvedCb.map(fn => fn());
}
let reject = reason => {
this.reason = reason;
this.status = REJECTED;
this.rejectedCb.map(fn => fn());
}
try {
exec(resolve, reject);
}catch (e) {
console.log(e, 'err');
}
}
then(onResolve, onReject){
return new MyPromise((resolve, reject) => {
if(this.status === RESOLVED){
let value = onResolve(this.value);
resolve(value);
}else if(this.status === REJECTED){
let reason = onReject(this.reason);
reject(reason);
}else{
this.resolvedCb.push(() => {
let value = onResolve(this.value);
resolve(value);
})
this.rejectedCb.push(() => {
let reason = onReject(this.reason);
reject(reason);
})
}
})
}
}
Promise.prototype.myRace([p1, p2]).then(() => console.log('test'))
Promise.prototype.myAll([p1, p2]).then(() => console.log('test'))
new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('p1');
}, 1000)
}).then(val => {
console.log(val);
return 'p2'
}).then(val => {
console.log('p2');
})
02-24
02-13
07-18
07-18
07-18
07-18
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交