今天俺尝试一下实现Promise
-
1.下面代码实现不了micro task,所以resolve后,then中回调的函数是立即执行的。
-
2.then方法的作用是加入成功、失败回调函数的入口,以及获取成功value,失败reason的地方
function CustomPromise(execute) {
this.status = 'pending';
this.value = undefined;
this.reason = '';
this.resolveCallback = [];
this.rejectCallback =[];
const ctx = this;
try {
execute(resolve, reject);
} catch (e) {
reject(e)
}
function resolve(value) {
if (ctx.status === 'pending') {
ctx.status = 'fulfilled'
ctx.value = value;
ctx.resolveCallback.forEach(fn => fn(value));
ctx.resolveCallback.length = 0;
}
}
function reject(reason) {
if (ctx.status === 'pending') {
ctx.