什么时候在 js Promise 上下文中调用finally?
我一开始以为finally
将在最后一个 then
之后调用。但后来我明白了,不可能确定最后一个then
。我的以下尝试也证明了这一点:
function f(resolve, reject) {
resolve("foo");
};
var p = new Promise(f);
p.then(function(data) {
console.log("data: " + data);
});
p.finally(function(data) {
console.log("in finally");
});
p.then(function(data) {
console.log("data: " + data);
});
输出:
data: foo
in finally
data: foo
所以,finally
在最后一个 then
之后没有被调用。我认为finally
应该在 resolve
之后调用然后。但在我上面尝试的示例代码中,我们可以看到情况并非如此(因为注册的 then
在 resolve
和 finally
之间被调用)。
因此,我很困惑,不明白finally
什么时候会出现?被召唤。
最佳答案
.finally
补充了 then
和 catch
:then
block 在执行时被调用,catch
在拒绝时被调用,并且 finally
在两种情况下都会被调用(例如:您进行 API 调用,在 then
block 中处理数据,在 catch
block 显示错误消息,在 finally
block 中隐藏加载微调器)。
然后链条继续。
Promise.reject('execute some action')
.then(() => console.log('I\'ll handle success here'))
.catch(() => console.log('error handling'))
.finally(() => console.log('this block will be executed either way'))
.then(() => console.log('and the adventure continues'))
关于javascript - js Promise 上下文中的finally 何时被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59435450/