谈谈promise的易错点吧

promise作为ES6里面的“大部头”,说简单也不是很难,说难吧感觉也确实挺难。下面我总结一下我自己关于promise的一些易错点和注意点,以及promise源码相关吧。

1.Promise 构造函数是同步执行,promise.then 是异步执行,并且是微任务。上代码。

const prom = new Promise((res, rej) => {
  console.log('first');
  res();
  console.log('second');
});
prom.then(() => {
  console.log('third');
});
console.log('fourth');

// first
// second
// fourth
// third

 2.一旦 resolve 和 reject 同时存在,只会执行第一个,后面的不再执行。上代码。

const prom = new Promise((res, rej) => {
  res('1');
  rej('error');
  res('2');
});

prom
  .then(res => {
    console.log('then: ', res);
  })
  .catch(err => {
    console.log('catch: ', err);
  });

// then: 1

3.一个 promise的then 或catch可以被多次调用,但是此处Promise构造函数仅执行一次。 换句话说,一旦promise 的内部状态发生变化并获得了一个值,则随后对then或catch的每次调用都将直接获取该值。 上代码。

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    console.log('first')
    resolve('second')
  }, 1000)
})

const start = Date.now()
promise.then((res) => {
  console.log(res, Date.now() - start, "third")
})
promise.then((res) => {
  console.log(res, Date.now() - start, "fourth")
})

// first
// second 1054 third
// second 1054 fourth

4.在then或catch 中返回错误对象不会引发错误,因此后续的catch 不会捕获该错误对象,返回resolve。上代码。

Promise.resolve()
  .then(() => {
    return new Error('error');
  })
  .then(res => {
    console.log('then: ', res);
  })
  .catch(err => {
    console.log('catch: ', err);
  });

// then: Error: error!

 

 

5.then或catch的参数应为函数,而传递非函数将导致值的结果被忽略。上代码。

Promise.resolve(1)
  .then(2)
  .then(Promise.resolve(3))
  .then(console.log)

  // 1

6. then接受的两个函数参数中,第一个sucess方法里面抛出错误,并列的fail接受不到,下一层链式调用才可以接受到。上代码。

Promise.resolve()
  .then(
    function success(res) {
      throw new Error('Error after success');
    },
    function fail1(e) {
      console.error('fail1: ', e);
    }
  )
  .catch(function fail2(e) {
    console.error('fail2: ', e);
  });

//   fail2:  Error: Error after success

以上我觉得就是promise 里面的易错点,需要额外去记忆。总结的不全面也可能有些不正确的地方,欢迎大家指正交流!!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值