promise
promise
- Promise 就是一个类 在执行这个类的时候 需要传递一个执行器进去 执行器会立即执行
- Promise 中有三种状态 分别为 成功 fulfilled 失败 rejected 等待 pending
pending -> fulfilled
pending -> rejected
一旦状态确定就不可更改 - resolve和reject函数是用来更改状态的
resolve: fulfilled
reject: rejected - then方法内部做的事情就判断状态 如果状态是成功 调用成功的回调函数 如果状态是失败 调用失败回调函数 then方法是被定义在原型对象中的
- then成功回调有一个参数 表示成功之后的值 then失败回调有一个参数 表示失败后的原因
- 同一个promise对象下面的then方法是可以被调用多次的
- then方法是可以被链式调用的, 后面then方法的回调函数拿到值的是上一个then方法的回调函数的返回值
// new Promise((resolve, reject) => {
// resolve('成功')
// // reject("失败"),状态确定后,不能更改
// })
const MyPromise = require('./myPromise');
function p1 () {
return new MyPromise(function (resolve, reject) {///执行器执行了,
setTimeout(function () {///发现里面有异步代码,主线程当中的代码,是不会等待异步代码执行的。等主线程完成才去执行异步。
// 因为没有resolve或reject修改状态,所以状态仍旧是pending,所以then方法中需要处理此情况(即异步情况)
// 如果是pennding状态,应该将当前的成功和失败回调存储起来
// resolve和reject中需要判断,成功和失败回调是否存在,如果存在,则直接执行。
resolve('p1')
}, 2000)
})
}
function p2 () {
return new MyPromise(function (resolve, reject) {
// reject('失败')
resolve('p2');
})
}
// 先调用p1再调用p2,按照正常执行顺序,应当输出p2,p1,但all调用时,会输出p1p2,会按照异步代码调用的顺序,得到结果
// MyPromise.all(['a', 'b', p1(), p2(), 'c']).then(value => console.log(value))
// Promise.resolve(10).then(value=>console.log(value))
p2().finally(() => {
console.log('finallly')
return p1()///返回一个promise(),如果直接return value,不会等待两秒
}).then((value) => {
console.log(value);//resolve('p2'); 输出p2 ------等待两秒后输出
}, (reason) => {
console.log(reason);//reject('失败')输出失败
})
p2()
.then(value => console.log(value))
.catch(reason => console.log(reason))
const PENDING = 'pending'; // 等待
const FULFILLED = 'fulfilled'; // 成功
const REJECTED = 'rejected'; // 失败
class MyPromise {
constructor (executor) {
try {
executor(this.resolve, this.reject)
} catch (e) {
this.reject(e);
}
}
// promsie 状态
status = PENDING;
// 成功之后的值
value = undefined;
// 失败后的原因
reason = undefined;
// 成功回调
successCallback = [];
// 失败回调
failCallback = [];
///resolve和reject定义为箭头函数的原因,因为直接调用时,可以将this指向,promise对象,如果普通函数,this
// 指向window或undefined
resolve = value => {
// 状态更改后,不能再次更改,只能pending下才能更改
// 如果状态不是等待 阻止程序向下执行
if (this.status !== PENDING) return;
// 将状态更改为成功
this.status = FULFILLED;
// 保存成功之后的值
this.value = value;
// 判断成功回调是否存在 如果存在 调用
// this.successCallback && this.successCallback(this.value);
while(this.successCallback.length) this.successCallback.shift()()
}
reject = reason => {
// 如果状态不是等待 阻止程序向下执行
if (this.status !== PENDING) return;
// 将状态更改为失败
this.status = REJECTED;
// 保存失败后的原因
this.reason = reason;
// 判断失败回调是否存在 如果存在 调用
// this.failCallback && this.failCallback(this.reason);
while(this.failCallback.length) this.failCallback.shift()()///循环数去组,去调用回调函数,shift()弹出当前需要执行的回调函数
}
then (successCallback, failCallback) {
// 参数可选
successCallback = successCallback ? successCallback : value => value;
// 参数可选
failCallback = failCallback ? failCallback: reason => { throw reason };
let promsie2 = new MyPromise((resolve, reject) => {
// 判断状态
if (this.status === FULFILLED) {
setTimeout(() => {
try {
let x = successCallback(this.value);
// 判断 x 的值是普通值还是promise对象
// 如果是普通值 直接调用resolve
// 如果是promise对象 查看promsie对象返回的结果
// 再根据promise对象返回的结果 决定调用resolve 还是调用reject
resolvePromise(promsie2, x, resolve, reject)
}catch (e) {
reject(e);
}
}, 0)
}else if (this.status === REJECTED) {
setTimeout(() => {
try {
let x = failCallback(this.reason);
// 判断 x 的值是普通值还是promise对象
// 如果是普通值 直接调用resolve
// 如果是promise对象 查看promsie对象返回的结果
// 再根据promise对象返回的结果 决定调用resolve 还是调用reject
resolvePromise(promsie2, x, resolve, reject)
}catch (e) {
reject(e);
}
}, 0)
} else {
// 等待
// 将成功回调和失败回调存储起来,链式调用时,有多个回调函数,所以需要数组存储
this.successCallback.push(() => {
setTimeout(() => {
try {
let x = successCallback(this.value);
// 判断 x 的值是普通值还是promise对象
// 如果是普通值 直接调用resolve
// 如果是promise对象 查看promsie对象返回的结果
// 再根据promise对象返回的结果 决定调用resolve 还是调用reject
resolvePromise(promsie2, x, resolve, reject)
}catch (e) {
reject(e);
}
}, 0)
});
this.failCallback.push(() => {
setTimeout(() => {
try {
let x = failCallback(this.reason);
// 判断 x 的值是普通值还是promise对象
// 如果是普通值 直接调用resolve
// 如果是promise对象 查看promsie对象返回的结果
// 再根据promise对象返回的结果 决定调用resolve 还是调用reject
resolvePromise(promsie2, x, resolve, reject)
}catch (e) {
reject(e);
}
}, 0)
});
}
});
return promsie2;
}
finally (callback) {
return this.then(value => {
// callback()
// return value
return MyPromise.resolve(callback()).then(() => value);
// 通过resolve,不管返回的是promise还是普通值,都去返回,可以等待callback中的p1执行完
}, reason => {
// callback()
// throw reason
return MyPromise.resolve(callback()).then(() => { throw reason })
})
}
catch (failCallback) {///不传递reject,处理失败回调方法
return this.then(undefined, failCallback)
}
static all (array) {///静态方法,所有成功才成功,一个失败则失败
let result = [];
let index = 0;
return new MyPromise((resolve, reject) => {
function addData (key, value) {///接收
result[key] = value;
index++;
if (index === array.length) {
resolve(result);
}
}
for (let i = 0; i < array.length; i++) {///在里面有异步操作,需要等所有异步操作完成,才能执行resolve
let current = array[i];
if (current instanceof MyPromise) {
// promise 对象
current.then(value => addData(i, value), reason => reject(reason))
}else {
// 普通值
addData(i, array[i]);
}
}
// resolve(result);不可在此,会中断后续的异步操作,结果会出现空值,使用index,等待异步操作完成
})
}
// resolve()方法,将给定的值转换为一个promise对象
static resolve (value) {
if (value instanceof MyPromise) return value;///接收的是promise的对象,直接返回
return new MyPromise(resolve => resolve(value));///不是promise对象,创建包裹给定值的promise对象返回
}
}
function resolvePromise (promsie2, x, resolve, reject) {
if (promsie2 === x) {
return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
}
if (x instanceof MyPromise) {
// promise 对象
// x.then(value => resolve(value), reason => reject(reason));
x.then(resolve, reject);
} else {
// 普通值
resolve(x);
}
}
module.exports = MyPromise;
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/613fcce5a10cbe7e4ff656f009cfd64f.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7306d9406cf4d162c7213a3aff23486d.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/b183b43dc2ff6974d36058e5f4597719.png)