我有以下 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/