js Promise 上下文中的finally 何时被调用?

hel*_*rld 3 javascript finally promise

js Promise 上下文中的finally 何时被调用?

我一开始以为 thefinally会在最后一个之后被调用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); 
});
Run Code Online (Sandbox Code Playgroud)

输出:

data: foo
in finally
data: foo
Run Code Online (Sandbox Code Playgroud)

因此,finally在最后一个之后不会调用then。我认为应该在thenfinally之后调用thethe resolve。但在我上面尝试的示例代码中,我们可以看到情况也并非如此(因为注册then是在resolve和 之间调用的finally)。

因此,我很困惑,不明白什么时候会被finally调用。

mbo*_*jko 5

.finally补充thencatchthen块在履行时被调用,在catch拒绝时被调用,并且finally在两种情况下都被调用(例如:您进行API调用,在then块中处理数据,在catch块中显示错误消息,在finally块中隐藏加载旋转器)。

然后链条继续。

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'))
Run Code Online (Sandbox Code Playgroud)