javascript之手写一个promise

promise

promise 的三个状态:pending(未完成)、fulfilled(完成)、reject(拒绝)

一个常见操作:

new Promise((resolve, reject) => {
   
  //一些请求
  this.$axios
    .get("/", {
    params: {
    id: id } })
    .then(res => {
   
      resolve(res); //返回成功后获取的值
    })
    .catch(err => {
   
      reject(err); // 失败
    });
})
  .then(resData => {
   
    //do something
    console.log(resData);
  })
  .catch(err => {
   
    console.log(err);
  });

promise 构造函数里面接收了两个函数作为参数,一个 resolve 和一个 reject,如果成功则返回成功数据

class Promise2 {
   
  constructor(fn) {
   
    this._queue = [];
    this._succ_mes = null;
    this._error_mes = null;
    this.status = "";

    fn(
      // 传入的匿名函数
      (...arg) => {
   
        // resolve
        this._succ_mes = arg;
        this.status = "succ";
      },
      (...arg) => {
   
        // reject
        this._error_mes = arg;
        this.status = "err";
      }
    );
  }

  then(fn1, fn2) {
   
    // then的两个函数参数
    if (this.status === "succ") {
   
      fn1(...this._succ_mes);
    } else if (this.status === "err") {
   
      if (fn2) {
   
        // then是否有第二个函数参数,有则在第二个函数里抛出reject错误,没有则在第一个函数里抛出
        fn2(...this._error_mes);
        return;
      }
      fn1(...this._succ_mes);
    } else {
   
      this._queue.push({
    fn1, fn2 });
    }
  }
}

以上实现了一个简易的 promise,可以达到的功能有:返回成功状态后的值|返回失败状态值|then 函数的两个函数参数返回值

下面增加 then 的链式调用

class Promise2 {
   
  constructor(fn) 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值