javascript中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);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值