【问题标题】:Resolve promise in another promise's chain and stop that chain解决另一个 Promise 链中的 Promise 并停止该链
【发布时间】:2017-03-11 13:06:19
【问题描述】:

我想做一些简单的事情:我希望我的函数返回一个 promise(1)。这个 promise(1) 将使用另一个 promise(2) 来执行任务。 Promise(2) 链接到多个 then/catch 步骤。在这些步骤中,promise(1) 可能需要解决/拒绝。 promise(2) 链需要停止执行,因为现在 promise(1) 已解决/拒绝并且应该停止运行。

最好的方法是什么?

参见以下示例代码:

function performDiv(a, b) {
    return new Promise(function (res, rej) { // promise(2)
        if (b === 0) {
            return rej(new Error('div by 0'));
        }
        res(a / b);
    })
}

function div(a, b) {
    return new Promise(function (res, rej) { // promise(1)
        performDiv(a, b)
        .then(res) // <--- HERE I want to break the chain
        .catch(rej) // <--- OR HERE, if there's a problem
        .then(function () {
            console.log('I don\'t want this to be shown')
        });
    });
}

div(10, 2)
.then(function (result) {
    console.log(result);
})
.catch(function (err) {
    console.log(err);
});

目前,I don't want this to be shown(为了解决 promise(1) 的假设的下一步)显示,而我想找到一个不是的解决方案,因为 promise(1) 已经解决/拒绝.

【问题讨论】:

  • 没有显示是异步的。为什么你需要承诺呢?
  • 只需删除 then'I don't want this to be shown'。这不是一个玩笑。如果你已经解决/拒绝了一个承诺(我什至没有在这里采取嵌套承诺的错误方法),那么为什么要添加一些你不想执行的东西呢?如果这是解决promise(1) 的假设步骤,那么您就没有抓住重点。如果 promise 1 没有被解决或拒绝,你就无法到达那里。这就是then 背后的全部想法
  • 各位,你们错过了重点,我可能是罪魁祸首。假设链有一些 if/then 以 maymay not 解决 promise(1)。如果唯一没有解决/拒绝承诺的事情,那么链条可能会继续。同步代码只是一个例子。
  • 另外,对我来说,在链完成之前可以拒绝承诺似乎很现实。如何拒绝承诺并破坏链条?
  • 你可以试试conditional code in a promise chain。另外,您使用的是catch to resume,考虑到您所说的,这似乎是错误的。你也可以考虑Promise.race,即使它实际上并没有停止另一条链。

标签: javascript node.js es6-promise


【解决方案1】:

我认为这里的问题是对 Promise 工作原理的误解。

打破承诺链的唯一方法是抛出一个错误,直到结束才捕获它。

让我们以你的为例。

function div(a, b) {
    return new Promise(function (res, rej) { // promise(1)
        performDiv(a, b)
        .then(res) // <--- HERE I want to break the chain (A)
        .catch(rej) // <--- OR HERE, if there's a problem (B)
        .then(function () { // (C)
            console.log('I don\'t want this to be shown')
        });
    });
}

A 和 B 都可能引发错误以破坏 then-ables 的链。

如果 (A) 抛出错误,B 将捕获它。在 B 中,您正在调用拒绝函数,它将 Promise 1 设置为被拒绝,但是它继续执行 Promise 2 上的剩余链,因为 rej 方法返回一个值(它可能是未定义的),这使得该承诺(一个 catch 返回)解决。

带走:每个thencatch 自己都返回一个Promise。断链抛出错误,直到最后才捕捉到它。

【讨论】:

    猜你喜欢
    • 2023-03-31
    • 2016-06-29
    • 2019-07-05
    • 2019-08-03
    • 1970-01-01
    • 2018-01-24
    • 2021-09-09
    • 1970-01-01
    • 2018-11-14
    相关资源
    最近更新 更多