最简单的promise完成了,接着就要完善then方法:
代码语言:javascript复制//...
//处理返回结果
function resolvePromise(promise2, x, resolve, reject) {
};
class Promise {
//...
//then方法,一个成功函数,一个失败函数
then(onFulfilled, onRejected){
//如果传进来的不是函数(不传也算),要忽略,赋值一个函数
// 错误函数要抛出错误才能进入reject
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : y => y;
onRejected = typeof onRejected === 'function' ? onRejected : r => {throw r};
//then必需返回一个promise,因为要传递成功失败结果
// 给下一个then,所以把方法都放入这个方法
let promise2 = new Promise((resolve, reject) => {
//如果成功,执行成功函数
if(this.state === FULFILLED){
/*成功或者失败函数返回一个值x,如果报错直接reject
每个人写的promise不同,但是要兼容符合规范的promise
要对x进行兼容处理,返回普通值、方法、对象,其它人的promise实例等
这边要先使用微任务MutationObserver、process.nextTick
如果不兼容微任务才使用宏任务setTimeout、setImmediate
这边直接用setTimeout
*/
setTimeout(() => {
try{
let x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject)
}catch (e) {
reject(e);
};
}, 0);
};
//如果失败,执行失败函数
if(this.state === REJECTED){
setTimeout(() => {
try{
let x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject)
}catch (e) {
reject(e);
};
}, 0);
};
//如果有异步,订阅成功、失败函数
if(this.state === PENDING){
this.onResolvedCallbacks.push(() => {
setTimeout(() => {
try{
let x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject)
}catch (e) {
reject(e);
};
}, 0);
});
this.onRejectedCallbacks.push(() => {
setTimeout(() => {
try{
let x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject)
}catch (e) {
reject(e);
};
}, 0);
});
};
});
//返回promise
return promise2;
}
}
(完)