一、实现Promise
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
class MPromise {
FULFILLED_CALLBACK_LIST = [];
REJECTED_CALLBACK_LIST = [];
_status = PENDING;
constructor(fn) {
// 初始状态为pending
this.status = PENDING;
this.value = null;
this.reason = null;
try {
fn(this.resolve.bind(this), this.reject.bind(this));
} catch (e) {
this.reject(e);
}
}
get status() {
return this._status;
}
set status(newStatus) {
this._status = newStatus;
switch (newStatus) {
case FULFILLED: {
this.FULFILLED_CALLBACK_LIST.forEach(callback => {
callback(this.value);
});
break;
}
case REJECTED: {
this.REJECTED_CALLBACK_LIST.forEach(callback => {
callback(this.reason);
});
break;
}
}
}
resolve(value) {
if (this.status === PENDING) {
this.value = value;
this.status = FULFILLED;
}
}
reject(reason) {
if (this.status === PENDING) {
this.reason = reason;
this.status = REJECTED;
}
}
then(onFulfilled, onRejected) {
const realOnFulfilled = this.isFunction(onFulfilled) ? onFulfilled : (value) => {
return value
}
const realOnRejected = this.isFunction(onRejected) ? onRejected : (reason) => {
throw reason;
};
const promise2 = new MPromise((resolve, reject) => {
const fulfilledMicrotask = () => {
queueMicrotask(() => {
try {
const x = realOnFulfilled(this.value);
this.resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e)
}
})
};
const rejectedMicrotask = () => {
queueMicrotask(() => {
try {
const x = realOnRejected(this.reason);
this.resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
})
}
switch (this.status) {
case FULFILLED: {
fulfilledMicrotask()
break;
}
case REJECTED: {
rejectedMicrotask()
break;
}
case PENDING: {
this.FULFILLED_CALLBACK_LIST.push(fulfilledMicrotask)
this.REJECTED_CALLBACK_LIST.push(rejectedMicrotask)
}
}
})
return promise2
}
catch (onRejected) {
return this.then(null, onRejected);
}
isFunction(param) {
return typeof param === 'function';
}
resolvePromise(promise2, x, resolve, reject) {//这个方法是处理onFulfilled的执行结果x,使promise2的value是基本值
// 如果 newPromise 和 x 指向同一对象,以 TypeError 为据因拒绝执行 newPromise
// 这是为了防止死循环
if (promise2 === x) {
return reject(new TypeError('The promise and the return value are the same'));
}
if (x instanceof MPromise) {
// 如果 x 为 Promise ,则使 newPromise 接受 x 的状态
// 也就是继续执行x,如果执行的时候拿到一个y,还要继续解析y
queueMicrotask(() => {
x.then((y) => {
this.resolvePromise(promise2, y, resolve, reject);
}, reject);
})
} else if (typeof x === 'object' || this.isFunction(x)) {
// 如果 x 为对象或者函数
if (x === null) {
// null也会被判断为对象
return resolve(x);
}
let then = null;
try {
// 把 x.then 赋值给 then
then = x.then;
} catch (error) {
// 如果取 x.then 的值时抛出错误 e ,则以 e 为据因拒绝 promise
return reject(error);
}
// 如果 then 是函数
if (this.isFunction(then)) {
let called = false;
// 将 x 作为函数的作用域 this 调用
// 传递两个回调函数作为参数,第一个参数叫做 resolvePromise ,第二个参数叫做 rejectPromise
try {
then.call(
x,
// 如果 resolvePromise 以值 y 为参数被调用,则运行 resolvePromise
(y) => {
// 需要有一个变量called来保证只调用一次.
if (called) return;
called = true;
this.resolvePromise(promise2, y, resolve, reject);
},
// 如果 rejectPromise 以据因 r 为参数被调用,则以据因 r 拒绝 promise
(r) => {
if (called) return;
called = true;
reject(r);
});
} catch (error) {
// 如果调用 then 方法抛出了异常 e:
if (called) return;
// 否则以 e 为拒因拒绝 promise
reject(error);
}
} else {
// 如果 then 不是函数,以 x 为参数执行 promise
resolve(x);
}
} else {
// 如果 x 不为对象或者函数,以 x 为参数执行 promise
resolve(x);
}
}
static resolve(value) {
if (value instanceof MPromise) {
return value;
}
return new MPromise((resolve) => {
resolve(value);
});
}
static reject(reason) {
return new MPromise((resolve, reject) => {
reject(reason);
});
}
//`const p = Promise.race([p1, p2, p3]);` 该方法是将多个 Promise 实例,包装成一个新的 Promise 实例。只要p1、p2、p3之中有一个实例率先改变状态,p的状态就跟着改变。那个率先改变的 Promise 实例的返回值,就传递给p的回调函数。race有赛跑的意思,也就是谁快用谁。
static race(promiseList) {
return new MPromise((resolve, reject) => {
const length = promiseList.length;
if (length === 0) {
return resolve();
} else {
for (let i = 0; i < length; i++) {
MPromise.resolve(promiseList[i]).then(
(value) => {
return resolve(value);//以111为value值调了resolve后状态改为FULFILLED,value改为111。222再调resolve时进不去更新value的值,所以value一直是111。(同一个promise,执行resolve时,只在状态为PENDING时才能进去更新值)。
},
(reason) => {
return reject(reason);
});
}
}
});
}
//`const p = Promise.all([p1, p2, p3]);` 该方法是将多个Promise实例包装成一个新的Promise实例。p1、p2、p3全部成功p才算成功,有一个出错,p就被认定为失败。成功的时候返回的是一个结果数组(此数组将会按照参数内的 promise 顺序排列,而不是由调用 promise 的完成顺序决定),失败的时候返回最先被reject失败状态的值。
static all(promiseList) {
return new MPromise(function(resolve, reject) {
var resolvedCounter = 0
var promiseNum = promiseList.length
var resolvedValues = new Array(promiseNum)
for (var i = 0; i < promiseNum; i++) {
(function(i) {//确保按promiseList数组的顺序
MPromise.resolve(promiseList[i]).then(function(value) {
resolvedCounter++
resolvedValues[i] = value
if (resolvedCounter == promiseNum) {
return resolve(resolvedValues)
}
}, function(reason) {
return reject(reason)
})
})(i)
}
})
}
}
二、调用Promise.race
const test = new MPromise((resolve, reject) => {
setTimeout(() => {
resolve(111);
}, 1000);
});
const test2 = new MPromise((resolve, reject) => {
setTimeout(() => {
resolve(222);
}, 2000);
});
const test3 = new MPromise((resolve, reject) => {
setTimeout(() => {
resolve(333);
}, 3000);
});
MPromise.race([test, test2, test3]).then(console.log);//输出 111
三、调用Promise.all
const p1 = new MPromise((resolve, reject) => {
resolve('成功了')
})
const p2 = new MPromise((resolve, reject) => {
resolve('success')
})
const p3 = new MPromise((resolve, reject) => {
setTimeout(() => {
reject('失败3000');
}, 3000);
});
const p4 = new MPromise((resolve, reject) => {
setTimeout(() => {
reject('失败1000');
}, 1000);
});
MPromise.all([p1, p2]).then((result) => {
console.log(result) //输出 ['成功了', 'success']
}).catch((error) => {
console.log(error)
})
MPromise.all([p1,p2,p3,p4]).then((result) => {
console.log(result)
}).catch((error) => {
console.log(error) // 输出 '失败1000'
})