Promise出现的原因我们不在赘述,不过是避免回调地狱之类的问题,下面我们就直接开始!请认真读完并理解每一行代码!
一、从零开始,手写Promise
1、Promise/A+
我们想要手写一个Promise
,就要遵循Promise/A+规范,业界所有Promise的类库都遵循这个规范
其实Promise/A+规范对如何实现一个符合标准的Promise类库已经阐述的很详细了。每一行代码在Promise/A+规范中都有迹可寻,所以在下面实现的过程中,尽可能的将代码和Promise/A+规范一一对应起来。
2、基础版Promise
回顾一下最简单的Promise“使用”方式
const p1 = new Promise((resolve,reject)=>{
console.log('create a promise')
resolve('成功了')
})
console.log('after new promise')
const p2 = p1.then(data =>{
console.log(data)
throw new Error('失败了')
})
const p3 = p2.then(data=>{
console.log('success',data)
},err=>{
console.log('faild',err)
})
控制台输出:"create a promise"
"after new promise"
"成功了"
"faild Error: 失败了"
- 首先我们在调用Promise时,会返回一个Promise对象
- 构建Promise对象时,需要传入一个executor函数,Promise的主要业务流程都在executor函数中执行
- 如果运行在executor函数中的业务执行成功了,会调用resolve函数,如果执行失败了,则调用reject函数
- Promise的状态不可逆,同事调用resolve函数和reject函数,默认会采取第一次调用的结果
以上简单介绍了Promise的一些主要的使用方法,结合Promise/A+规范,我们可以分析出Promise一下的基本特征:
Promise有三个状态:pending、fulfilled、rejected
new Promise时,需要传递一个executor()执行器,执行器立即执行
executor接受两个参数,分别是resolve和reject;
Promise的默认状态是pending;
Promise有一个value保存成功状态的值,可以是undefined/promise
promise有一个reason保存失败状态的值
promise只能从pending到rejected,或者充pending到fulfilled,状态一旦确定,就不会再更改
promise必须有一个then方法,then接受两个参数,分别是promise成功的回调onFulfilled,和promise失败的回调onRejected
如果调用then时,promise已经失败,那么执行onRejected,参数时promise的reason
如果调用then时已经成功,那么执行onFulfilled,参数时promise的value
如果then中抛出了异常,那么就会把这个一场作为参数,传递给下一个then的失败的回调onRejected
按照上面的特征,我们来写一下
//三个状态
const PENDING = 'PENDING'
const FULFILLED = 'FULFILLED'
const REJECTED = 'REJECTED'
class Promise {
constructor(executor) {
this.status = PENDING //默认状态为PENDING
this.value = undefined //存放成功状态的值,默认为undefined
this.reason = undefined //存放失败状态的值,默认为undefined
let resolve = value => {
//调用此方法就是成功
//状态为PENDING时才可以更新状态,防止executor中调用两次resolve/reject方法
if(this.status === PENDING) {
this.status = FULFILLED
this.value = value
}
}
let reject = reason =>{
//调用此方法就是失败
//状态为PENDING时才可以更新状态,防止executor中调用两次resolve/reject方法
if(this.status === PENDING) {
this.status = REJECTED
this.reason = reason
}
}
try {
// 立即执行,将 resolve 和 reject 函数传给使用者
executor(resolve,reject)
} catch (error) {
// 发生异常时执行失败逻辑
reject(error)
}
}
then(onFulfilled,onRejected) {
if(this.status === FULFILLED) {
onFulfilled(this.value)
}
if(this.status === REJECTED) {
onRejected(this.reason)
}
}
}
写完代码测试一下
const promise = new Promise((resolve,reject)=>{
resolve('成功')
}).then(data=>{
console.log('success',data);
},err=>{
console.log('faild',err);
})
控制台输出:'success 成功'
现在我们已经实现了一个基础版的Promise,但是还不要高兴太早,这里我们只处理了同步操作的Promise。如果在executor()中传入一个异步操作的话呢,试一下
const promise = new Promise((resolve,reject)=>{
setTimeout(()=>{
console.log('成功')
},1000)
}).then(data=>{
console.log('success',data);
},err=>{
console.log('faild',err);
})
执行测试代码后发现,promise没有返回
因为promise调用then方法时,当前的promise并没有成功,一直处于pending状态。所以如果当调用then方法时,当前状态是pending,我们需要先将成功和失败的回调分别存放起来,在executor()的异步任务被执行时,出发resolve或reject,一次嗲用失败或成功的回调
结合思路,优化代码
const PENDING = 'PENDING'
const FULFILLED = 'FULFILLED'
const REJECTED = 'REJECTED'
class Promise {
constructor(executor) {
this.status = PENDING
this.value = undefined
this.reason = undefined
this.onResolvedCallbacks = [] // 存放成功的回调
this.onRejectedCallbacks = [] // 存放失败的回调
let resolve = value =>{
this.status = FULFILLED
this.value = value
//依次将对应的函数执行
this.onResolvedCallbacks.forEach(fn=>fn())
}
let reject = reason =>{
this.status = REJECTED
this.reason = reason
//依次将对应的函数执行
this.onRejectedCallbacks.forEach(fn=>fn())
}
try {
executor(resolve,reject)
} catch (error) {
reject(error)
}
}
then(onFulfilled,onRejected) {
if(this.status === FULFILLED) {
onFulfilled(this.value)
}
if(this.status === REJECTED) {
onRejected(this.reason)
}
if(this.status === PENDING) {
// 如果Promise的状态是pending,需要将 onFulfilled 和 onRejected 函数存放起来等待状态确定后,再依次将对应的函数执行
this.onResolvedCallbacks.push(()=>{
onFulfilled(this.value)
})
this.onRejectedCallbacks.push(()=>{
onRejected(this.reason)
})
}
}
}
测试一下:
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('成功');
},1000);
}).then(
(data) => {
console.log('success', data)
},
(err) => {
console.log('faild', err)
}
)
控制台1s后输出:'success 成功'
3、then的链式调用&值穿透特性
我们都知道,Promise的优势在于可以链式调用。在我们使用Promise的时候,当then函数中return了一个值,不管是什么值,我们都能在下一个then中获取到,这就是所谓的then链式调用。而且当我们不在then中放入参数。例:promise.then().then()
,那么其后面的then一九可以得到之前then返回的值,这就是所谓的值的穿透。那具体如何实现的呢?简单思考一下,如果每次调用then的时候,我们都重新创建一个promise对象,并把上一个then的返回结果传给这个新的promise的then方法,不久可以一致then下去了吗,那我们来试着实现一下,这也是手写promise源码的重中之重。
then的参数onFulfilled和onRejected 可以缺省,如果onFulfilled或者onRejected不是函数,将其忽略,且一九可以在下面的then中获取到之前返回的值
promise可以then多次,每次执行完promise.then方法后返回的都是一个新的promise
如果then的返回值x是一个普通值,那么就会把这个结果作为参数,传递给下一个then的成功回调中
如果then抛出了异常,,那么就会把这个异常作为阐述,传递给下一个then的失败的回调中
如果then的返回值x是一个promise,那么就会等这个promise执行完,promise如果成功,就走下一个then的成功,如果失败,就走下一个then的失败,如果抛出异常,就走下一个then的失败
如果then的返回值X和promise是同一个引用对象,造成循环引用,则抛出异常,把异常传递给下一个then失败的回调中
如果then的返回值X是一个promise。且X同时调用resolve函数和reject函数,则第一次调用优先,其他函数调用被忽略
我们将代码补充完整:
const PENDING = 'PENDING';
const FULFILLED = 'FULFILLED';
const REJECTED = 'REJECTED';
const resolvePromise = (promise2, x, resolve, reject) => {
// 自己等待自己完成是错误的实现,用一个类型错误,结束掉 promise Promise/A+ 2.3.1
if (promise2 === x) {
return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
}
// Promise/A+ 2.3.3.3.3 只能调用一次
let called;
// 后续的条件要严格判断 保证代码能和别的库一起使用
if ((typeof x === 'object' && x != null) || typeof x === 'function') {
try {
// 为了判断 resolve 过的就不用再 reject 了(比如 reject 和 resolve 同时调用的时候) Promise/A+ 2.3.3.1
let then = x.then;
if (typeof then === 'function') {
// 不要写成 x.then,直接 then.call 就可以了 因为 x.then 会再次取值,Object.defineProperty Promise/A+ 2.3.3.3
then.call(x, y => { // 根据 promise 的状态决定是成功还是失败
if (called) return;
called = true;
// 递归解析的过程(因为可能 promise 中还有 promise) Promise/A+ 2.3.3.3.1
resolvePromise(promise2, y, resolve, reject);
}, r => {
// 只要失败就失败 Promise/A+ 2.3.3.3.2
if (called) return;
called = true;
reject(r);
});
} else {
// 如果 x.then 是个普通值就直接返回 resolve 作为结果 Promise/A+ 2.3.3.4
resolve(x);
}
} catch (e) {
// Promise/A+ 2.3.3.2
if (called) return;
called = true;
reject(e)
}
} else {
// 如果 x 是个普通值就直接返回 resolve 作为结果 Promise/A+ 2.3.4
resolve(x)
}
}
class Promise {
constructor(executor) {
this.status = PENDING;
this.value = undefined;
this.reason = undefined;
this.onResolvedCallbacks = [];
this.onRejectedCallbacks= [];
let resolve = (value) => {
if(this.status === PENDING) {
this.status = FULFILLED;
this.value = value;
this.onResolvedCallbacks.forEach(fn=>fn());
}
}
let reject = (reason) => {
if(this.status === PENDING) {
this.status = REJECTED;
this.reason = reason;
this.onRejectedCallbacks.forEach(fn=>fn());
}
}
try {
executor(resolve,reject)
} catch (error) {
reject(error)
}
}
then(onFulfilled, onRejected) {
//解决 onFufilled,onRejected 没有传值的问题
//Promise/A+ 2.2.1 / Promise/A+ 2.2.5 / Promise/A+ 2.2.7.3 / Promise/A+ 2.2.7.4
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v;
//因为错误的值要让后面访问到,所以这里也要跑出个错误,不然会在之后 then 的 resolve 中捕获
onRejected = typeof onRejected === 'function' ? onRejected : err => { throw err };
// 每次调用 then 都返回一个新的 promise Promise/A+ 2.2.7
let promise2 = new Promise((resolve, reject) => {
if (this.status === FULFILLED) {
//Promise/A+ 2.2.2
//Promise/A+ 2.2.4 --- setTimeout
setTimeout(() => {
try {
//Promise/A+ 2.2.7.1
let x = onFulfilled(this.value);
// x可能是一个proimise
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
//Promise/A+ 2.2.7.2
reject(e)
}
}, 0);
}
if (this.status === REJECTED) {
//Promise/A+ 2.2.3
setTimeout(() => {
try {
let x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e)
}
}, 0);
}
if (this.status === 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);
});
}
});
return promise2;
}
}
测试一下:
const promise = new Promise((resolve,reject)=>{
reject('失败');
}).then().then().then(data => {
console.log(data)
},err=>{
console.log('err',err)
})
控制台输出:"失败 err"