今天在写Promise.finally实现的时候,发现总有一个case过不去,感觉很奇怪,为啥我的跑了多次

错误演示

async function myFinally(promise, onFinally) {
  try {
    await onFinally();
    return promise;
  } catch(error) {
    await onFinally();
    throw error;
  }
}

经过断点发现我的onFinally 跑了两次,我就???,我记得Promise里面的是已经包含了catch了啊,所以就不用捕获了

case实例

myFinally(promise, () => {
  console.log('执行');
  res.push(1)
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      res.push(2)
      reject(4)
    }, 100)
  })
}).then((value) => {
  res.push(3)
}).catch((reason) => {
  // expect(res).toEqual([1, 2])
  console.log('res:', res);
  console.log('reason:', reason);
  // expect(reason).toBe(4)
  // done()
})

后来想了下这个myFinally里面是异步的await Promise.reject(),这样执行的时候会阻塞后面的同步代码执行,所以此时如果awit一个失败的Promise,则会被之后的catch捕获

Last modification:June 16, 2022
If you think my article is useful to you, please feel free to appreciate