这将处理该表的
species
除以下详细说明的行为外:
Promise.prototype.finally = Promise.prototype.finally || {
finally (fn) {
const onFinally = callback => Promise.resolve(fn()).then(callback);
return this.then(
result => onFinally(() => result),
reason => onFinally(() => Promise.reject(reason))
);
}
}.finally;
finally()
取决于
then()
符合规范要求:
-
A.
finally
回调将不会收到任何参数,因为没有可靠的方法来确定承诺是履行了还是拒绝了。这个用例正好适用于您不关心拒绝原因或履行价值的情况,因此不需要提供它。
-
不像
Promise.resolve(2).then(() => {}, () => {})
undefined
),
Promise.resolve(2).finally(() => {})
将通过以下方式解决:
2
.
-
类似地,不像
Promise.reject(3).then(() => {}, () => {})
(这将以
未定义
),
Promise.reject(3).finally(() => {})
将被拒绝与
3
.
A.
throw
最后
throw()
.
当然,这是一个等价行为的演示:
const logger = (label, start = Date.now()) => (...values) => {
console.log(label, ...values, `after ${Date.now() - start}ms`);
};
const delay = (value, ms) => new Promise(resolve => {
setTimeout(resolve, ms, value);
});
// run test on native implementation
test('native');
// force Promise to use the polyfill implementation
Promise.prototype.finally = /* Promise.prototype.finally || */ {
finally (fn) {
const onFinally = callback => Promise.resolve(fn()).then(callback);
return this.then(
result => onFinally(() => result),
reason => onFinally(() => Promise.reject(reason))
);
}
}.finally;
// run test on polyfill implementation
test('polyfill');
function test (impl) {
const log = ordinal => state => logger(`${ordinal} ${impl} ${state}`);
const first = log('first');
// test propagation of resolved value
delay(2, 1000)
.finally(first('settled'))
.then(first('fulfilled'), first('rejected'));
const second = log('second');
// test propagation of rejected value
delay(Promise.reject(3), 2000)
.finally(second('settled'))
.then(second('fulfilled'), second('rejected'));
const third = log('third');
// test adoption of resolved promise
delay(4, 3000)
.finally(third('settled'))
.finally(() => delay(6, 500))
.then(third('fulfilled'), third('rejected'));
const fourth = log('fourth');
// test adoption of rejected promise
delay(5, 4000)
.finally(fourth('settled'))
.finally(() => delay(Promise.reject(7), 500))
.then(fourth('fulfilled'), fourth('rejected'));
}
.as-console-wrapper{max-height:100%!important}
幸亏
@Bergi
his implementation
如果你觉得这篇文章有帮助的话,也可以投票。