gpt4 book ai didi

javascript - ES6 promise 解决回调?

转载 作者:IT王子 更新时间:2023-10-29 03:06:20 25 4
gpt4 key购买 nike

无论我的 Promise 是否成功解决,我都想运行相同的操作。我不想将相同的函数绑定(bind)到 .then 的两个参数。难道没有像 jQuery 那样的 .always 吗?如果没有,我该如何实现?

最佳答案

Isn't there a .always like jQuery has?

不,there's not (yet) .虽然有一个 active proposal ,所以也许是 ES2018。
是的,有:promise .finally()是自 ES2018 以来标准的一部分。

If not, how do I achieve this?

你可以像这样自己实现finally方法:

Promise.prototype.finally = function(cb) {
const res = () => this
const fin = () => Promise.resolve(cb()).then(res)
return this.then(fin, fin);
};

或更广泛地说,将解析信息传递给回调:

Promise.prototype.finally = function(cb) {
const res = () => this
return this.then(value =>
Promise.resolve(cb({state:"fulfilled", value})).then(res)
, reason =>
Promise.resolve(cb({state:"rejected", reason})).then(res)
);
};

两者都确保维持原始决议(当回调中没有异常时)并等待 promise 。

关于javascript - ES6 promise 解决回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32362057/

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