【问题标题】:How to fix the return type of the last promise in a chain?如何修复链中最后一个承诺的返回类型?
【发布时间】:2016-02-13 16:42:45
【问题描述】:

我想将链中的最后一个 Promise 作为函数的结果返回。我正在使用 TypeScript 1.7 和原生的 ES6 承诺。

我试过这个,但 TS 认为第一个承诺是返回值(Uint8Array),而不是 importKey 中的 CryptoKey。我见过让我认为最后一个承诺实际上是返回值的 JavaScript 示例,所以也许 TS 只是混淆了?

private getKey(): Promise<Uint8Array> {
    return localforage.getItem<Uint8Array>("key")
        .then<Uint8Array>((derivedKeyData) => {
            return crypto.subtle.importKey("raw", derivedKeyData, { name: "AES-GCM" }, false, ["decrypt"]);
        });
}

如何将内部承诺作为函数的结果返回?或者至少在不使函数的返回类型为“任何”的情况下让 TS 相信这就是真正发生的事情?

【问题讨论】:

  • 我不知道 TS,所以我只会评论:您立即返回 localForage.getItem,这就是您的类型签名必须匹配的原因。要解决这个问题,您必须用return new Promise&lt;CryptoKey&gt;(resolve, reject) =&gt; ... 包裹整个方法体,并让importKey 调用resolve() .. 类似importKey(...).then(resolve).catch(reject)
  • @Matt 我从这条路线开始,这似乎可行,但后来我意识到我的打字错误,正如我在答案下面提到的那样。

标签: javascript typescript promise es6-promise


【解决方案1】:

我在 http://www.typescriptlang.org/Playground 上查看了您的代码,问题似乎是 importKey 的内置结果类型是“任何”

【讨论】:

  • 这个答案让我找到了正确的答案——then 的类型是为了表示下一个 promise 的输出类型,也是函数的返回类型。所以这个函数实际上是返回链中的最后一个承诺,我只是把我的类型弄错了。例如。 return localforage.getItem("x").then&lt;CryptoKey&gt;((forageItem)=&gt;{ return crypto.importKey(...); }) 这适用于我的情况,因为即使在 TS 定义中 importKey 在我的使用中返回 any 它是 CryptoKey
猜你喜欢
  • 1970-01-01
  • 2023-01-27
  • 2015-11-27
  • 1970-01-01
  • 2017-09-16
  • 1970-01-01
  • 2015-06-05
  • 1970-01-01
  • 2016-11-23
相关资源
最近更新 更多