1. 什么是 promise
从语义上可以看出,它是一个承诺,承诺一段时间后给你反馈一个结果。
从语法上,它是一个有then方法的对象,使用new来创建。
它会有三种状态,等待pending、成功resolve、失败rejecte,且一旦状态确定,就无法更改,此时它成了不变值,所以,一个Promise,不能有两种状态赋予。
Promise创建的任务是微任务。
2. promiseA+ 规范是什么
1,不管进行什么操作,都返回一个Promise对象,类似于jquery的链式操作;
2,一个 Promise 的当前状态必须为以下三种状态中的一种:
等待态(Pending)、执行态(Fulfilled)和拒绝态(Rejected)。
-
pending
1.1 初始的状态, 可改变.
1.2 ⼀个promise在resolve或者reject前都处于这个状态。
1.3 可以通过 resolve fulfilled 状态;
1.4 可以通过 reject rejected 状态 -
fulfilled
2.1 最终态, 不可变.
2.2 ⼀个promise被resolve后会变成这个状态.
2.3 必须拥有⼀个value值 -
rejected
3.1 最终态, 不可变.
3.2 ⼀个promise被reject后会变成这个状态
3.3 必须拥有⼀个reason值即,pending => resolve(value) => fulfilled pending => reject(reason) => rejected
3.then()
Promise提供了⼀个then⽅法, ⽤来访问最终的结果, ⽆论是value还是reason。
1.每个then()都是一个准备态的Promise对象。
2.是否在promise中return。
3.每个then()会处理离自己最近的那个promise
4. ⽤queueMicrotask来实现微任务的调⽤
//queueMicrotask
// queueMicrotask()创建一个微任务
// 效果和使用Promise一样的,都是将任务加入微任务队列
// 待宏任务结束后依次执行
queueMicrotask(fn);
//概念
promise.then(onFulfilled, onRejected)
//实际操作
new Promise((resolve, reject) => {
resolve("操作成功!");
reject("拒绝! ");
//成功拒绝两个状态 分别对应的是value 和 reason
})
.then(
value => {
console.log("成功业务处理 1");
}, //
reason => {
console.log("拒绝的业务处理");
}
)
1. 参数要求
1.1 onFulfilled 必须是函数类型, 如果不是函数, 应该被忽略.
1.2 onRejected 必须是函数类型, 如果不是函数, 应该被忽略.
2. onFulfilled/onRejected 特性
2.1 在promise变成 fulfilled/rejected 时,应该调⽤ onFulfilled/onRejected, 参数是value
2.2 在promise变成 fulfilled/rejected 之前, 不应该被调⽤.
2.3 只能被调⽤⼀次(所以在实现的时候需要⼀个变量来限制执⾏次数)
3. then⽅法可以被调⽤多次
5.1 promise状态变成 fulfilled 后,所有的 onFulfilled 回调都需要按照then的顺序执⾏, 也就
是按照注册顺序执⾏(所以在实现的时候需要⼀个数组来存放多个onFulfilled的回调)
5.2 promise状态变成 rejected 后,所有的 onRejected 回调都需要按照then的顺序执⾏, 也
就是按照注册顺序执⾏(所以在实现的时候需要⼀个数组来存放多个onRejected的回调)
4. resolvePromise
resolvePromise(promise2, x, resolve, reject)
4.1 如果 promise2 和 x 相等,那么 reject TypeError
4.2 如果 x 是⼀个 promsie
(1).如果x是pending态,那么promise必须要在pending,直到 x 变成 fulfilled or rejected.
(2).如果 x 被 fulfilled, fulfill promise with the same value.
(3).如果 x 被 rejected, reject promise with the same reason.
4.3 如果 x 是⼀个 object 或者 是⼀个 function
let then = x.then.
a.如果 x.then 这步出错,那么 reject promise with e as the reason.
b.如果 then 是⼀个函数,then.call(x, resolvePromiseFn, rejectPromise)
resolvePromiseFn 的 ⼊参是 y, 执⾏ resolvePromise(promise2, y, resolve, reject);
rejectPromise 的 ⼊参是 r, reject promise with r.
c.如果 resolvePromise 和 rejectPromise 都调⽤了,那么第⼀个调⽤优先,后⾯的调⽤忽略。
d.如果调⽤then抛出异常e
e. 如果 resolvePromise 或 rejectPromise 已经被调⽤,那么忽略
则,reject promise with e as the reason
f.如果 then 不是⼀个function. fulfill promise with x
3.完整构建Promise
// 定义三种状态类型
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
//用 class 实现基本promise
class MPromise {
// 创建两个数组用于储存 成功/ 失败 的回调
FULFILLED_CALLBACK_LIST = [];
REJECTED_CALLBACK_LIST = [];
_status = PENDING;
constructor(fn) {
// 初始状态为pending
this.status = PENDING;
this.value = null;
this.reason = null;
try {
fn(this.resolve.bind(this), this.reject.bind(this));
} catch (e) {
this.reject(e);
}
}
/*. ⽤getter和setter,在status发⽣变化的时候, 就执⾏所有的回调,去做要做的事情.
(当然也可以顺序执⾏, 在给status赋值后, 下⾯再加⼀⾏forEach) */
get status() {
return this._status;
}
// 在对象内如果设置了存取器属性,如果某一变量只声明了getter方法,那么它仅仅只可读而不可写。如果只声明了setter方法,那么读到的该变量值永远都是undefined。
/*一、getter
1、按照客户的期望返回格式化数据。
2、控制服务的顺序(例如只有当连接建立时getter方法才返回相应实例)。
二、setter
1、可以限制和检验setter方法传入的参数。
2、隐藏对象内部数据结构。*/
set status(newStatus) {
this._status = newStatus;
switch (newStatus) {
case FULFILLED: {
this.FULFILLED_CALLBACK_LIST.forEach(callback => {
callback(this.value);
});
break;
}
case REJECTED: {
this.REJECTED_CALLBACK_LIST.forEach(callback => {
callback(this.reason);
});
break;
}
}
}
// 定义 resolve 和 reject 方法 函数的⼊参分别是value 和 reason.
//states 从padding 改到 fulfilled/rejected
resolve(value) {
if (this.status === PENDING) {
this.value = value;
this.status = FULFILLED;
}
}
reject(reason) {
if (this.status === PENDING) {
this.reason = reason;
this.status = REJECTED;
}
}
//then 方法之前 isfunction 函数用于检测传入的是不是函数
isFunction(param) {
return typeof param === ‘function’;
}
//then⽅法
then(onFulfilled, onRejected) {
// 根据当前promise的状态, 调⽤不同的函数
const fulFilledFn = this.isFunction(onFulfilled) ? onFulfilled : (value) => {
return value;
}
const rejectedFn = this.isFunction(onRejected) ? onRejected : (reason) => {
throw reason;
};
const fulFilledFnWithCatch = (resolve, reject, newPromise) => {
queueMicrotask(() => {
try {
if (!this.isFunction(onFulfilled)) {
resolve(this.value);
} else {
const x = fulFilledFn(this.value);
this.resolvePromise(newPromise, x, resolve, reject);
}
} catch (e) {
reject(e)
}
})
};
const rejectedFnWithCatch = (resolve, reject, newPromise) => {
queueMicrotask(() => {
try {
if (!this.isFunction(onRejected)) {
reject(this.reason);
} else {
const x = rejectedFn(this.reason);
this.resolvePromise(newPromise, x, resolve, reject);
}
} catch (e) {
reject(e);
}
})
}
//存入数组
switch (this.status) {
case FULFILLED: {
const newPromise = new MPromise((resolve, reject) => fulFilledFnWithCatch(resolve, reject, newPromise));
return newPromise;
}
case REJECTED: {
const newPromise = new MPromise((resolve, reject) => rejectedFnWithCatch(resolve, reject, newPromise));
return newPromise;
}
case PENDING: {
const newPromise = new MPromise((resolve, reject) => {
this.FULFILLED_CALLBACK_LIST.push(() => fulFilledFnWithCatch(resolve, reject, newPromise));
this.REJECTED_CALLBACK_LIST.push(() => rejectedFnWithCatch(resolve, reject, newPromise));
});
return newPromise;
}
}
}
// 如果 onFulfilled 或者 onRejected 返回⼀个值 x ,则运⾏resolvePromise⽅法
resolvePromise(newPromise, x, resolve, reject) {
// 如果 newPromise 和 x 指向同一对象,以 TypeError 为据因拒绝执行 newPromise
// 这是为了防止死循环
if (newPromise === x) {
return reject(new TypeError('The promise and the return value are the same'));
}
if (x instanceof MPromise) {
// 如果 x 为 Promise ,则使 newPromise 接受 x 的状态
// 也就是继续执行x,如果执行的时候拿到一个y,还要继续解析y
x.then((y) => {
this.resolvePromise(newPromise, y, resolve, reject);
}, reject);
} else if (typeof x === 'object' || this.isFunction(x)) {
// 如果 x 为对象或者函数
if (x === null) {
// null也会被判断为对象
return resolve(x);
}
let then = null;
try {
// 把 x.then 赋值给 then
then = x.then;
} catch (error) {
// 如果取 x.then 的值时抛出错误 e ,则以 e 为据因拒绝 promise
return reject(error);
}
// 如果 then 是函数
if (this.isFunction(then)) {
let called = false;
// 将 x 作为函数的作用域 this 调用
// 传递两个回调函数作为参数,第一个参数叫做 resolvePromise ,第二个参数叫做 rejectPromise
try {
then.call(
x,
// 如果 resolvePromise 以值 y 为参数被调用,则运行 resolvePromise
(y) => {
// 需要有一个变量called来保证只调用一次.
if (called) return;
called = true;
this.resolvePromise(newPromise, y, resolve, reject);
},
// 如果 rejectPromise 以据因 r 为参数被调用,则以据因 r 拒绝 promise
(r) => {
if (called) return;
called = true;
reject(r);
});
} catch (error) {
// 如果调用 then 方法抛出了异常 e:
if (called) return;
// 否则以 e 为据因拒绝 promise
reject(error);
}
} else {
// 如果 then 不是函数,以 x 为参数执行 promise
resolve(x);
}
} else {
// 如果 x 不为对象或者函数,以 x 为参数执行 promise
resolve(x);
}
}
catch (onRejected) {
return this.then(null, onRejected);
}
/*将现有对象转为Promise对象,如果 Promise.resolve ⽅法的参数,不是具有 then ⽅法的对
象(⼜称 thenable 对象),则返回⼀个新的 Promise 对象,且它的状态为fulfilled。*/
static resolve(value) {
if (value instanceof MPromise) {
return value;
}
return new MPromise((resolve) => {
resolve(value);
});
}
/*返回⼀个新的Promise实例,该实例的状态为rejected。Promise.reject⽅法的参数reason,
会被传递给实例的回调函数。*/
static reject(reason) {
return new MPromise((resolve, reject) => {
reject(reason);
});
}
static race(promiseList) {
return new MPromise((resolve, reject) => {
const length = promiseList.length;
if (length === 0) {
return resolve();
} else {
for (let i = 0; i < length; i++) {
MPromise.resolve(promiseList[i]).then(
(value) => {
return resolve(value);
},
(reason) => {
return reject(reason);
});
}
}
});
}
}
const test = new MPromise((resolve, reject) => {
setTimeout(() => {
resolve(111);
}, 1000);
}).then(console.log);
console.log(test);
setTimeout(() => {
console.log(test);
}, 2000)