一、我们先看看promise怎么使用
const promise = new Promise(function(resolve, reject) {
// ... some code
if (/* 异步操作成功 */){
resolve(value);
} else {
reject(error);
}
});
promise.then(function(value) {
// success
}, function(error) {
// failure
});
可以看出Promise是一个类,实例化需要传一个回调函数,函数传递resolve和reject用来改变状态。
函数里面resolve接收一个值,在then第一个回调函数作为参数传入。reject方法接收一个error值,在then的第二个回调函数参入。
then方法两个参数为函数,一个是Promise状态改为fulfilled传递的参数,一个是Rejected是传递的error参数。
二、实现一个基础Promise类
const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";
class PromiseM {
status = PENDING; // promise 状态
value = undefined; // 成功之后的值
error = undefined; // 失败后的原因
constructor(fn) {
return fn(this.resolve, this.reject);
}
resolve = (value) => {
// 如果状态不是等待 组织程序向下执行
if (this.status !== PENDING) return
// 将状态更改为成功
this.status = FULFILLED;
// 保存成功后的值
this.value = value;
};
reject = (error) => {
// 如果状态不是等待 组织程序向下执行
if (this.status !== PENDING) return
// 将状态更改为失败
this.status = REJECTED;
// 保存失败后的原因
this.error = error;
};
then = (successCallBack, failCallBack?) => {
if (this.status === FULFILLED) {
return successCallBack(this.value);
}
if (this.status === REJECTED) {
return failCallBack(this.error);
}
throw false;
};
}
调用
const promiseM = new PromiseM((resolve, reject) => {
resolve(1);
// reject('fail')
}).then((res) => {
console.log(res);
}, error => {
console.log(error);
});
三、完善Promise
1、需要处理异步情况 2、then方法多次调用 3、then方法可以返回一个值或者一个全新Promise对象,后面then方法参数是上一个then方法的返回值。
4、处理错误
异步处理:
const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";
class PromiseM {
status = PENDING; // promise 状态
value = undefined; // 成功之后的值
error = undefined; // 失败后的原因
successCallBack = undefined;
failCallBack = undefined;
constructor(fn) {
return fn(this.resolve, this.reject);
}
resolve = (value) => {
// 如果状态不是等待 组织程序向下执行
if (this.status !== PENDING) return
// 将状态更改为成功
this.status = FULFILLED;
// 保存成功后的值
this.value = value;
// 判断成功回调是否存在,如果存在则调用
this.successCallBack && this.successCallBack(this.value)
};
reject = (error) => {
// 如果状态不是等待 组织程序向下执行
if (this.status !== PENDING) return
// 将状态更改为失败
this.status = REJECTED;
// 保存失败后的原因
this.error = error;
// 判断失败回调是否存在,如果存在则调用
this.failCallBack && this.failCallBack(this.value)
};
then = (successCallBack, failCallBack?) => {
if (this.status === FULFILLED) {
return successCallBack(this.value);
}
if (this.status === REJECTED) {
return failCallBack(this.error);
}
this.successCallBack = successCallBack
this.failCallBack = failCallBack
};
}