class mypromise {
constructor(fun) {
//fun 就是相当于 (resolve, rejest) => {}
this.status = "pading";
this.value = "";//promise状态为fulfilled时,定义一个形参来接收传递的参数
this.errval = "";//promise状态为rejected时,定义一个变量来接受传递的参数
//异步处理
this.succlist = [];//定义一个集合存放成功的回调函数
this.errlist = [];//定义一个集合存放失败时的回调函数
let resol = (value) => { //resolve函数处理时传递参数
if (this.status == "pading") {//promise的状态从pading=>fulfilled (只能由进行中->成功 或者 由进行中->失败)
this.status = "fulfilled";
this.value = value;//赋值
//遍历数组,执行方法
this.succlist.forEach(element => {
element(this.value);
});
}
}
let rejec = (errval) => {//reject函数处理时也需传递参数
if (this.status == "pading") {//promise的状态从pading=>rejected
this.status = "rejected";
this.errval = errval;//赋值
this.errlist.forEach(element => {
element(this.errval);
});
}
}
try {
fun(resol, rejec);//调用
} catch (err) {
console.log(err)
}
}
//Promise实例生成以后,可以用then方法分别指定resolved状态和rejected状态的回调函数。 因此再定义个then()方法
then(succ, error) {//then方法可以接受两个回调函数作为参数
//succ就是 Promise对象的状态变为resolved时调用
//error就是 Promise对象的状态变为rejected时调用
this.succlist.push(succ);//存放成功时的回调函数
this.errlist.push(error);//存放失败时的回调函数
if (this.status == "fulfilled") {
succ(this.value);//传入参数即可
} else if (this.status == "rejected") {
error(this.errval);
}
}
}
var promise = new mypromise((resolve, rejest) => {
//resolve("这是成功时的结果");
//rejest("这是失败时的数据");//传递实参
//异步处理
setTimeout(() => {
//resolve("这是成功时的结果");
rejest("这是失败时的数据");
}, 1000)
})
promise.then(res => {
console.log(res)
}, err => {
console.log(err)
})
class封装promise
最新推荐文章于 2023-07-10 16:21:04 发布