gpt4 book ai didi

javascript - promise 链如何引用下一个错误处理程序

转载 作者:IT老高 更新时间:2023-10-28 23:16:32 26 4
gpt4 key购买 nike

我想知道是否有人知道 promise 链如何引用下一个错误处理程序 - 例如:

  const p = new Promise(resolve => resolve(5))
.then(v => 5*v)
.then(v => { throw 'foo' });

p.then(v => v/4)
.then(v => v+3)
.catch(e => console.error('first catch:', e));

p.then(v => v/4)
.then(v => v+3)
.catch(e => console.error('second catch:', e));

如果你运行它,你会得到:

first catch: foo
second catch: foo

据我所知,每次调用 Promise.prototype.then 时,都会创建并返回一个新的 Promise。为了保证能够为每个链找到 下一个错误处理程序,我能想到的唯一方法是拥有一个对子项的引用数组。因此,如果一个 Promise 被拒绝,它会遍历所有子 Node ,并在每个子链中找到最近的拒绝处理程序。

有人知道这是怎么实现的吗?

最佳答案

我的看法:

将 Promise 视为嵌套数组:

[then1,[then1.1, then1.2, catch1.1, then1.3, then1.4], then2, catch1]

看起来像这样:

new Promise(...)
.then(() => { // <- 1
return Promise(...)
.then() // <- 1.1
.then() // <- 1.2
.catch() // <- 1.1
.then() // <- 1.3
.then() // <- 1.4
})
.then() // <- 2
.catch() // <- 1

现在假设我们开始执行,它从最顶层的数组开始。我们对每个数组都有一个索引,指定我们在执行方面等待哪个元素。我们首先调用 .then1,它本身返回一个 Promise 链(另一个数组)。当错误发生时,您在层次结构数组中的最低层(最深的)跳过(不执行)它是元素,直到找到 catch。如果是,它执行 catch 并继续执行其他元素。如果它没有找到 catch,它会要求父数组找到并执行 catch,跳过所有元素包括它的子数组,因为它们不是 catch

在我们的示例中,如果 then1.2 发生错误,它将被 catch1.1 捕获,但如果发生在 then1.3 code> 它将一直传播到 catch1 跳过 then1.4then2

编辑:

下面是试验代码:

new Promise(res => res())
.then(() =>
new Promise(res => res())
.then(() => console.log(1))
.then(() => {console.log(2); throw "Error 1"})
.catch((err) => console.log(err))
.then(() => {console.log(3); throw "Error 2"}))
.then(() => console.log(4))
.then(() =>
new Promise(res => res())
.then(() => console.log(6))
.then(() => {console.log(7); throw "Error 3"})
.catch((err) => console.log(err))
.then(() => console.log(8))
.then(() => {console.log(9); throw "Error 4"}))
.then(() => console.log(10))
.catch((err) => console.log(err))

它记录:

1

2

Error 1

3

Error 2

关于javascript - promise 链如何引用下一个错误处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50884487/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com