javascript - Promise.finally 没有作为链的最后一次调用返回

标签 javascript ecmascript-6 es6-promise

我有以下 promise 链,我期望 .finally() 的解析函数 promise 返回,但最后一个 .then() 是返回的。

exportReportToJson (url,opts) {
    const requestJSON = {
      "values" : []
    };

    return this.getValue(url)
    .then( value => {
      requestJSON.values.push(value);
      if(opts.extraValue){
        return this.getExtraValue(value);
      }else{
        return Promise.finally();
      }
    })
    //The index of .push gets returned instead
    .then(extraValue => requestJSON.values.push(extraValue))
    //But I want requestJSON to always be the returned Promise
    .finally( () => requestJSON)
}

正如你所看到的,我希望最终永远是要返回的最终 promise ,这不是目的吗?我在这里缺少什么?我认为它可以作为 .always()

请稍候。

我想要一个有条件的 .then,同时基本上不改变最终的 .then。

最佳答案

.finally 不允许您更改 Promise 的解析结果;它只是用于执行拆卸逻辑。如果 Promise 以某个值解析,则它仍然以该值解析;如果它以某个值被拒绝,那么它仍然以该值被拒绝。

您可以在此处查看有关其行为的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally

如果需要更改值,请使用 .then 或 .catch。如果您还希望两者具有相同的逻辑,那么您需要同时使用两者。这要么意味着复制代码,要么将其提取到命名函数中。

关于javascript - Promise.finally 没有作为链的最后一次调用返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54185413/

相关文章:

javascript - 图像映射为圆形区域设置背景图像

javascript - Next Js - Firebase 部署问题

javascript - 如何拦截 then 或 catch 中的 Promise 响应?

javascript - 为什么我的脚本中多次触发点击事件?

JavaScript。如何禁止对象属性创建

javascript - 如何在 es6 中将对象值相乘

javascript - ES6减少返回1个数组项而不是2个

javascript - ES6 React JSX 返回一个对象而不是数组

javascript - Firebase:更新或创建

promise.prototype.finally 的 TypeScript 类型定义