// 1) 解决并发问题 (同步多个异步方法的执行结果)
// 2) 链式调用的问题 (现获取 name,通过name在获取age) 解决多个回调嵌套的问题
// Promise是一个类 可以按照这个思路手写promise
// 1)每次new 一个Promise 都需要传递一个执行器 ,执行器是立即执行的
// 2) 执行器函数中有两个参数 resolve,reject
// 3)默认Promise 有三个状态 pendding =》 resolve 表示成功了fulfilled reject就是拒绝 rejected
// 4) 如果一旦成功了 不能变成失败 一旦失败 不能在成功了 只有当前状态是pending的时候 才能更改状态
// 5) 每个promise都有一个then方法
const PENDING = "PENDING";
const FULFILLED = "FULFILLED";
const REJECTED = "REJECTED";
class Promise {
constructor(executor) { // executor 执行器
// 创建promise executor会立即执行
this.value = undefined;
this.reason = undefined;
this.status = PENDING;
let resolve = value => {
if (this.status === PENDING) {
this.value = value;
this.status = FULFILLED;
}
};
let reject = reason => {
if (this.status === PENDING) {
this.reason = reason;
this.status = REJECTED;
}
};
// 这里可能会发生异常
try {
executor(resolve, reject);
} catch (e) {
reject(e);
}
}
// then方法会判断当前的状态
then(onFulfilled, onRejected) {
if (this.status === FULFILLED) {
onFulfilled(this.value);
}
if (this.status === REJECTED) {
onRejected(this.reason);
}
}
}
// 导出当前类 commonjs定义方式
module.exports = Promise;
// 链式调用