- promise是一个类,执行类的时候需要传递一个执行器进去,执行器会立即执行
- promise 有三种状态 等待pending 成功fulfilled 失败rejected pending => fulfilled; pending => rejected 一旦状态确定就不可更改
- resolve和reject用来改变状态 resolve => fulfilled reject => rejected
- then 方法内部做的事情判断状态,如果状态是成功调成功函数 如果状态是失败调失败函数
- then 成功回调有一个参数表示成功之后的值,失败回调有一个参数表示失败后的原因
- 同一个promise对象下面的then方法是可以被多次调用的
- then 方法可以被链式调用,后面then方法的回调函数拿到值是上一个then方法的回调函数。
const PENDING = 'pending'; //等待
const FULFILLED = 'fulfilled'; // 成功
const REJECTED = 'rejected'; // 失败
class MyPromise {
constructor(executor) {
executor(this.resolve, this.reject)
}
// promise状态
status = PENDING;
// 成功之后的值
value = undefined
// 失败后的原因
reason = undefined
resolve = value => {
// 状态不是等待 阻止程序向下执行
if(this.status !== PENDING) return;
this.status = FULFILLED;
// 保存成功后的值
this.value = value;
}
reject = reason => {
// 状态不是等待 阻止程序向下执行
if(this.status !== PENDING) return;
this.status = REJECTED;
// 保存失败后的原因
this.reason = reason;
}
then (successCallback, failCallback) {
// 判断状态
if(this.status === FULFILLED){
successCallback(this.value);
} else if(this.status === REJECTED){
failCallback(this.reason);
}
}
}
module.exports = MyPromise;
- 抛出错误:promise对象自己返回自己,即发生循环调用,需要对用户抛出错误 通过setTimeout将代码变成异步代码来获取到promise2对象,通过判断回调对象和promise2是否是同一个来判断是否返回同一个promise.
myPromise.js
then (successCallback, failCallback) {
let promise2 = new MyPromise((resolve, reject) => { // TODO resolve对应then的value
// 判断状态
if(this.status === FULFILLED){
// 变为异步代码 来获取到promise2
setTimeout( ()=> {
let x = successCallback(this.value);
// 判断 x 值是普通值还是promise对象
// 如果是普通值 直接调用resolve
// 如果是promise对象 查看promise对象返回的结果
// 再根据promise对返回的结果,决定调用resolve还是reject
resolvePromise(promise2, x, resolve, reject)
},0);
} else if(this.status === REJECTED){
failCallback(this.reason);
} else { // 异步的情况
// 等待
// 将成功失败回调存储起来
this.successCallback.push(successCallback);
this.failCallback.push(failCallback);
}
})
return promise2;
}
function resolvePromise (promise2, x, resolve, reject) {
if(promise2 === x){
return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
}
if( x instanceof MyPromise) {
// promise 对象
x.then(resolve, reject); // TODO
} else {
// 普通值
resolve(x);
}
}
index.js
// 测试 对象自返回同一个promise报错信息提示
let p1 = promise.then(value => {
console.log(value);
return p1;
})
p1.then(value => {
console.log(value);
}, reason => {
console.log(reason.message);
})
- try catch 捕获请求的异常, then的下一个链式then获取到抛出的异常信息. 执行构造器时候捕获错误 then执行回调函数的地方的地方捕获错误
try {
executor(this.resolve, this.reject)
} catch (e) {
this.reject(e);
}
// 变为异步代码 来获取到promise2
setTimeout( ()=> {
try {
let x = successCallback(this.value);
// 判断 x 值是普通值还是promise对象
// 如果是普通值 直接调用resolve
// 如果是promise对象 查看promise对象返回的结果
// 再根据promise对返回的结果,决定调用resolve还是reject
resolvePromise(promise2, x, resolve, reject)
} catch (e) {
reject(e)
}
},0);
index.js
// 第二个链式then 获取到第一个then抛出的异常信息
promise.then(value => {
console.log(value)
throw new Error('then error')
}, reason => {
console.log(222,reason)
}).then(value => {
console.log(value)
}, reason => {
console.log(333,reason.message)
})
- then方法参数变成可选参数,参数可以传递到最后一个有回调函数的then。
myPromise.js
then (successCallback, failCallback) {
successCallback = successCallback ? successCallback : value => value;
failCallback = failCallback ? failCallback : reson => { throw reson};
....
}
index.js
promise.then().then().then(value => console.log(value), reason => console.log(reason))
- promise.all(): 解决异步并发问题的,按照异步代码调用顺序得到执行结果。返回值也是一个promise对象 所有状态有一个成功就是成功的 有一个失败的all失败 all里面有异步请求,需要等待所有结果都返回再resolve结果
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++) {
let current = array[i];
if(current instanceof MyPromise) {
// promise 对象
current.then( value => addData(i,value), reason => reject(reason))
} else {
// 普通值
addData(i, array[i]);
}
}
});
}
index.js
function p1 () {
return new MyPromise(function (resolve, reject){
// 异步
setTimeout(function () {
resolve('p1')
}, 2000)
})
}
function p2 () {
return new MyPromise(function (resolve, reject){
resolve('p2');
})
}
MyPromise.all(['a', 'b', p1(), p2(), 'c']).then(result => console.log(result));
打印结果 ['a','b','p1','p2','c']
- promise.resolve(): 将给定的值转换为promise对象
static resolve (value) {
if(value instanceof MyPromise) return value;
return new MyPromise(resolve => resolve(value));
}
MyPromise.resolve(100).then(value => console.log(value))
- finally: 特点1 无论当前promise对象最终状态是成功还是失败,finally方法中的回调函数都会被执行一次 特点2 finally方法后可以链式调用then方法来拿到当前promise对象最终的返回结果
finally (callback) {
return this.then(value => {
// 将回调结果都变为promise对象 并且等待异步回调结果返回后 再返回结果
return MyPromise.resolve(callback()).then(() => value);
}, reason => {
return MyPromise.resolve(callback()).then(() => { throw reason } );
});
}
p2().finally(() => {
console.log('finally')
return p1();
}).then(value => {
console.log(value)
}, reason => {
console.log(reason)
})
14 catch: 处理当前promise最终状态为失败的情况的 可以不传失败回调