极简版Promise 满足的运用体式格局
- 天生实例对象的体式格局:
new MyPromise()
- 经由过程类直接挪用静态要领:
MyPromise.resolve()
,现在静态要领仅支撑resolve
&reject
亲测运用OK,迎接指教,互相学习,github链接,迎接star。
附赠应用组织函数手写Promise 的要领,github链接。
class MyPromise {
constructor(fn) {
// 定义Promise 三种状况
this.states = {
PENDING: 'PENDING', RESOLVED: 'RESOLVED', REJECTED: 'REJECTED'
}
// 定义通报到then的value
this.value = null
// 定义当前Promise运转状况
this.state = this.states.PENDING
// 定义Promise失利状况的回调函数鸠合
this.resolvedCallBacks = []
// 定义Promise胜利状况的回调函数鸠合
this.rejectedCallBacks = []
// 为静态要领定义其内部运用的指向实例的that
MyPromise.that = this
try {
// 实行 new MyPromise() 内传入的要领
fn(MyPromise.resolve, MyPromise.reject)
} catch (error) {
MyPromise.reject(this.value)
}
}
// 静态resolve要领,MyPromise实例不可接见;
//支撑类MyPromise接见,例:MyPromise.resolve('success').then(e=>e)
static resolve(value) {
// 因为静态要领内部的this指向 类 而不是 实例,所以用下面的要领接见实例对象
const that = MyPromise.that
// 推断是不是是MyPromise实例接见resolve
const f = that instanceof MyPromise
// MyPromise实例对象接见resolve
if (f && that.state == that.states.PENDING) {
that.state = that.states.RESOLVED
that.value = value
that.resolvedCallBacks.map(cb => (that.value = cb(that.value)))
}
// MyPromise类接见resolve
if (!f) {
const obj = new MyPromise()
return Object.assign(obj, {
state: obj.states.RESOLVED,
value
})
}
}
// 静态reject要领,MyPromise实例不可接见;
//支撑类MyPromise接见,例:MyPromise.reject('fail').then(e=>e)
static reject(value) {
const that = MyPromise.that
const f = that instanceof MyPromise
if (f && that.state == that.states.PENDING) {
that.state = that.states.REJECTED
that.value = value
that.rejectedCallBacks.map(cb => (that.value = cb(that.value)))
}
if (!f) {
const obj = new MyPromise()
return Object.assign(obj, {
state: obj.states.REJECTED,
value
})
}
}
// 定义在MyPromise原型上的then要领
then(onFulfilled, onRejected) {
const { PENDING, RESOLVED, REJECTED } = this.states
const f = typeof onFulfilled == "function" ? onFulfilled : c => c;
const r =
typeof onRejected == "function"
? onRejected
: c => {
throw c;
};
switch (this.state) {
case PENDING:
// ‘PENDING’状况下向回调函数鸠合增加callback
this.resolvedCallBacks.push(f)
this.rejectedCallBacks.push(r)
break;
case RESOLVED:
// 将回调函数的返回值赋值给 实例的 value,满足链式挪用then要领时通报value
this.value = f(this.value)
break;
case REJECTED:
// 同上
this.value = r(this.value)
break;
default:
break;
}
// 满足链式挪用then,返回MyPromise实例对象
return this
}
}
MyPromise.resolve('success').then((e) => {
console.log(e);
return e + 1
}).then( res=> {
console.log(res);
})
new MyPromise(resolve => {
setTimeout(() => {
resolve(1);
}, 2000);
})
.then(res1 => {
console.log(res1);
return 2;
})
.then(res2 => console.log(res2 ));