Promise心得,2021年6月

背景

动机

以前写代码的时候遇到过这些,犯过错,今阅读文档有感,特此记录。

环境

node v14.7.0

心得

1. resolve和reject不能当return用

之前不知道这个,当return用,出过bug

resolve 证明

代码:

new Promise((resolve,reject) => {
    console.log(1);
    resolve(2);
    console.log(3);
}).then(v => console.log(v));
复制代码

打印结果:

1
3
2
复制代码

reject 证明

同上,略

2. new Promise(…)不写then/catch也能运行

代码:

new Promise((res,rej) => {
    console.log(1);
});
console.log(2); // 须注意
复制代码

打印结果:

2
1
复制代码

3. then/catch的跳过与传值

场景:之前做多步骤设置多个错误处理时遇到的。
比如,要实现这种需求:

promise调接口一
.catch(e=>{
    接口一的错误处理
    不能运行后面的
})
.then(res=>{
    处理一下数据,做成参数来调接口二
})
.catch(e=>{
    接口二的错误处理
})

复制代码

跳过catch

之前以为.then.catch.then的第二个then拿不到第一个then的值。
现在发现可以。

结论:不仅运行跨过去了,值也跨着传过去了(没错的话)

代码:

const 打印并传值 = (v) => {
  console.log(v);
  return v;
};
new Promise((res, rej) => {
  console.log(1);
  res(2);
})
  .catch((e) => console.log(e))
  .then(打印并传值)
  .catch((e) => console.log(e))
  .then(打印并传值);

复制代码

打印结果:

1
2
2
复制代码

catch跳不过then(catch里没错的话)

我根据结果来理解:catch抓到一个错误后就吃掉它了,对后面的代码来说,已经没有错误了。所以除非catch里throw个Error,或者return个触发reject的Promise,才会跳过then,到下一个最近的catch,否则执行then。
像这么看来,多步骤设置多个错误处理还挺麻烦的,因为要在catch里抛错,否则就执行后面的promise了。

  1. 跳不过的示例

代码:

const 打印并传值 = (v) => {
  console.log(v);
  return v;
};
new Promise((res, rej) => {
  console.log('处理中');
  rej('错误');
})
  .catch((e) => console.log(e))
  .then(打印并传值)
  .catch((e) => console.log(e))
  .then(打印并传值);
复制代码

运行结果:

处理中
错误
undefined
undefined
复制代码
  1. 跳1个then的示例

代码:

const 打印并传值 = (v) => {
  console.log(v);
  return v;
};
new Promise((res, rej) => {
  console.log('处理中');
  rej('错误');
})
  .catch((e) => {
    console.log(e)
    throw new Error('抛错')
  })
  .then(打印并传值)
  .catch((e) => {
    console.log(e)
  })
  .then(打印并传值);
复制代码

运行结果:

处理中
错误
Error: 抛错
undefined
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享