【问题标题】:Typescript - Why does AxiosPromise not have a property ".finally"? [duplicate]Typescript - 为什么 AxiosPromise 没有属性“.finally”? [复制]
【发布时间】:2018-12-31 08:32:20
【问题描述】:

我正在将一个 JS 文件转换为 TS。这是有问题的原始代码。

let refreshToken = null;

if (refreshToken == null) {
    refreshToken = // get the axios instance...
} 

refreshToken
.then(() => { // something })
.catch(() => { // something })
.finally(() => { // something });

所以我把它转换成:

let refreshToken : AxiosPromise | null = null;

if (refreshToken == null) {
    refreshToken = // get the axios instance...
} 

refreshToken
.then(() => { // something })
.catch(() => { // something })
.finally(() => { // something });

但是finally 给了我一个错误:

Promise 类型上不存在“finally”属性。

这是为什么呢?

我绕过它的方式就是写(refreshToken as any),但这似乎是一个逃避解决方案。 TypeScript 不应该能够推断出 refreshTokenAxiosPromise 吗?

【问题讨论】:

    标签: javascript typescript axios


    【解决方案1】:
    $ npm install axios promise.prototype.finally --save
    

    并将其添加到顶部

    require('promise.prototype.finally').shim();
    

    【讨论】:

      【解决方案2】:

      或者,您可以再附加一个.then 作为链的最后一部分。本机 Promise 示例(此行为应该相同)真/假如下:

      function fakeGet(passed) {
        return new Promise((resolve, reject) => setTimeout(passed ? resolve : reject, 1000));
      }
      
      function onComplete(passed) {
        console.log(passed ? 'Success' : 'Failed')
      }
      
      fakeGet(true)
      .then(() => true)
      .catch(() => false)
      .then(onComplete);
      
      fakeGet(false)
      .then(() => true)
      .catch(() => false)
      .then(onComplete);

      【讨论】:

        猜你喜欢
        • 2011-06-13
        • 1970-01-01
        • 2013-03-14
        • 2012-12-25
        • 2016-02-04
        • 1970-01-01
        • 2012-06-13
        • 2015-05-17
        • 1970-01-01
        相关资源
        最近更新 更多