手写 Promise
1. Promise/A+规范
有兴趣的同学可以去Promise/A+查看,下面只是简单的解读。
Promise
是一个对象或者函数。它有一个then
方法。
thenable
是一个对象或者函数,用来定义 >then
方法value
是 >Promise
状态成功时的值reason
是 >Promise
状态失败时的值>
2. 实现一个简单的 Promise
- 第一步,定义
Promise
实例的初始状态
function MyPromise(fn) {
const that = this;
that.state = 'pending'; // 初始状态
that.value = null; // 调用 resolve 时的参数值
that.reason = null; // 调用 reject 时的参数值
}
- 实现
resolve
和reject
方法
function MyPromise(fn) {
...
function resolve(value) {
if (that.state === 'pending') {
that.value = value; // 取到 resolve 的值
that.state = 'resolved' // 更改 状态
}
}
function reject(err) {
if (that.state === 'pending') {
that.reason = err;
that.state = 'rejected';
}
}
}
- 将
resolve
和reject
作为参数调用 fn
function MyPromise(fn) {
...
try {
fn(resolve, reject)
} catch(e) {
reject(e)
}
}
- 在
Promise
原型上定义then
方法
MyPromise.prototye.then = function(onFulfilled, onRejected) {
let self=this;
switch(self.status){
case "resolved":
onFullfilled(self.value);
break;
case "rejected":
onRejected(self.reason);
break;
default:
}
}