Promise原理:
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
class MyPromise {
status = PENDING; // 状态一经改变就不可变
value = null;
reason = null;
successCallback = null;
failCallback = null;
constructor(executor) {
this.resolve = this.resolve.bind(this);
executor(this.resolve, this.reject)
}
resolve(value) {
if (this.status !== PENDING) return;
this.status = FULFILLED;
this.value = value;
this.successCallback && this.successCallback(this.value);
}
reject = reason => {
if (this.status !== PENDING) return;
this.status = REJECTED;
this.reason = reason;
this.failCallback && this.failCallback(this.reason);
}
then(successCallback, failCallback) {
if (this.status === FULFILLED) {
successCallback(this.value);
} else if (this.status === REJECTED) {
failCallback(this.reason);
} else {
// 等待状态 把两个函数存起来 更改状态之后才能执行then方法
this.successCallback = successCallback;
this.failCallback = failCallback;
}
}
}
module.exports = MyPromise;
Async await原理:
function myAjax1() {
return new Promise(resolve => {
setTimeout(() => {
resolve('成功111');
}, 1000);
});
}
function myAjax2() {
return new Promise(resolve => {
setTimeout(() => {
resolve('成功222');
}, 1000);
});
}
function* fun() {
const myAjaxRes1 = yield myAjax1();
console.log(myAjaxRes1, 'myAjaxRes1');
const myAjaxRes2 = yield myAjax2();
console.log(myAjaxRes2, 'myAjaxRes2');
}
const f = fun();
// const fNext = f.next();
// console.log(fNext);
// fNext.value.then(res => {
// const fNext = f.next(res);
// fNext.value.then(res => {
// f.next(res);
// })
// })
function handle(res) {
if (res.done) return;
res.value.then(data => {
handle(f.next(data));
})
}
handle(f.next());