手撕Promise
👨🏼🦳👨🏼🦰 文件结构 以及 方法了解 🧓🏼
👇 index.html
👇 promise.js
接下来我们将封装 promise实例方法 👇
then
catch
接下来我们将封装 promise静态方法 👇
resolve
reject
all
race
01 - 搭建基本结构 🍠
index.html
let p = new Promise((resolve,reject) => {
})
promise.js
class Promise {
constructor(executor) {
}
}
02 - Promise中 resolve 和 reject 结构 🥩
index.html
let p = new Promise((resolve,reject) => {
resolve();
reject();
throw "errro";
})
promise.js
Promise 中有 三种 状态:
pending 未决定的
fulfilled 成功的
rejected 失败的
调用里面的 resolve 则状态改变为 fulfilled。
调用里面的 reject 则状态改变为 rejected。
如果什么都不写则状态默认为 pending。
如果在抛出错误则 返回一个 rejected 状态。
注意:
在 promise 中只能改变一次状态,则下面的代码会进行忽略。
class Promise {
constructor(executor) {
this.PromiseState = "pending";
this.PromiseResult = null;
var resolve = value => {
if (this.PromiseState != "pending") return;
this.PromiseState = "fulfilled";
this.PromiseResult = value;
}
var reject = reason => {
if (this.PromiseState != "pending") return;
this.PromiseState = "rejected";
this.PromiseResult = reason;
}
try {
executor(resolve,reject);
} catch (e) {
reject(e);
}
}
}
03 - Promise中 then 方法 🌯
index.html
let p = new Promise((resolve, reject) => {
setTimeout(() => {
// resolve('123');
reject("error");
}, 1000);
// reject("error");
// throw "error";
});
// console.log(p);
let res = p.then(
value => {
console.log(value);
// return "123";
return new Promise((resolve, reject) => {
// resolve("123");
reject("error");
// throw "error";
});
},
reason => {
console.log(reason);
// return "123";
return new Promise((resolve, reject) => {
// resolve("123");
// reject("error");
// throw "error";
});
}
);
console.log(res);
promise.js
class Promise {
constructor(executor) {
this.callBack = [];
this.PromiseState = "pending";
this.PromiseResult = null;
var resolve = value => {
if (this.PromiseState != "pending") return;
this.PromiseState = "fulfilled";
this.PromiseResult = value;
this.callBack.forEach(item => {
item.onResolved(value);
})
}
var reject = reason => {
if (this.PromiseState != "pending") return;
this.PromiseState = "rejected";
this.PromiseResult = reason;
this.callBack.forEach(item => {
item.onRejected(reason);