// 关于promise 是用来避免些很多回调
// 这里写一个正经的promise
// let pro = new Promise((resolve, reject) => {
// let num = Math.trunc( Math.random() * 10 )
// if(num > 5) {
// // 异步一下 走到这里会有一个输出 resolve 和 reject 里面的参数是执行完毕后的输出 也是then的参数
// setTimeout(() => {
// console.log("resolve");
// resolve("成功");
// }, 1000);
// } else{
// setTimeout(() => {
// console.log("reject");
// reject("失败");
// }, 1000);
// }
// });
// console.log(pro);
// pro.then(val => {
// console.log(val)
// }).then(val => {
// console.log(1111111,val)
// })
// 下面是自己实现一个promise
let MyPromise = function (res) {
/*
一个 Promise有以下几种状态:
pending: 初始状态,既不是成功,也不是失败状态。
fulfilled: 意味着操作成功完成。
rejected: 意味着操作失败。
进入到promise的时候 是pending状态
有 pending -> fulfilled
pending -> rejected
两种情况 没有第三种 而且不可逆
*/
let that = this;
// 先给个状态值
that.status = "pending";
// 保存将来可能传入的文本
that.value = "";
// 成功的回调集
that.fulfillCBArr = []
// 失败的回调集
that.rejectCBArr = [];
// 成功
function resolve (val) {
if (that.status === "pending"){
that.value = val;
that.status = "fulfilled";
console.log(val)
// 执行成功回调函数
that.fulfillCBArr.forEach(item => {
item()
});
}
}
// 失败
function reject(val) {
if (that.status === "pending") {
that.value = val;
that.status = "rejected";
console.log(val);
// 执行失败回调函数
that.rejectCBArr.forEach(item => {
item();
});
}
}
setTimeout(() => {
res(resolve, reject);
}, 10);
}
// then方法绑定
MyPromise.prototype.then = function(fulfillCB, rejectCB) {
let then_this = this
// 返回一个新的promise 用来实现链式
return new MyPromise(function (res, rej) {
if (then_this.status === "pending") {
then_this.fulfillCBArr.push(()=>{
let result = fulfillCB();
// 这里是为了链式调用时 及时修改新的promise的状态
// es6规范是 返回 undefined 会认为reject 还有一些其他情况 需要去查看文档 这里只是模拟了一下
// 如果是1 认为是成功状态 是2 认为是失败状态
if(result === 1) {
res(result)
} else if(result === 2) {
rej(result)
}
});
}
if (then_this.status === "fulfilled") {
if (typeof fulfillCB === "function") {
fulfillCB(then_this.value);
} else {
res(then_this.value);
}
}
if (then_this.status === "rejected") {
if (typeof rejectCB === "function") {
rejectCB(then_this.value);
} else {
rej(then_this.value);
}
}
});
};
// catch方法绑定 太麻烦了 不写了 catch有一个穿透的特性。。。 太麻烦了
MyPromise.prototype.catch = () => {};
let my = new MyPromise((resolve, reject) => {
let num = Math.trunc(Math.random() * 10);
if (num > 5) {
// 异步一下 走到这里会有一个输出 resolve 和 reject 里面的参数是执行完毕后的输出 也是then的参数
setTimeout(() => {
console.log("resolve");
resolve("成功");
}, 1000);
} else {
setTimeout(() => {
console.log("reject");
reject("失败");
}, 1000);
}
});
console.log(my)
my.then(() => {
console.log("then")
return 1
}).then(() => {
console.log("then2")
});
手动实现一个promise
最新推荐文章于 2024-04-26 09:23:58 发布