【问题标题】:In Typescript how to promisify a function while binding with type safety?在 Typescript 中,如何在绑定类型安全的同时承诺函数?
【发布时间】:2019-01-23 19:17:13
【问题描述】:

考虑以下承诺:

import { S3 } from 'aws-sdk'
import { promisify } from 'util'

const s3 = new S3({ apiVersion: '2006-03-01' })
const getObject = promisify<S3.GetObjectRequest, S3.GetObjectOutput>(
  s3.getObject
)

这很好用,除了你会得到像TypeError: this.makeRequest is not a function 这样的错误,因为s3.getObject 现在绑定到错误的this 范围。但是,这个:

const getObject = promisify<S3.GetObjectRequest, S3.GetObjectOutput>(
  s3.getObject.bind(s3)
)

破坏类型安全并会报错:Unsafe use of expression of type 'any'.(假设您使用严格模式)。

那么我怎样才能在 Typescript 中承诺像 s3 的 getObject 这样的东西呢?

【问题讨论】:

  • () =&gt; s3.getObject()

标签: javascript node.js typescript amazon-s3


【解决方案1】:

您可以传递另一个调用s3.getObject() 的函数,而无需绑定它。使用箭头函数,您只需很少的额外代码即可做到这一点。

const getObject = promisify<S3.GetObjectRequest, S3.GetObjectOutput>(
  name => s3.getObject(name)
)

但是,AWS SDK 运算符函数通常有一个 .promise 方法,该方法返回一个承诺,而不是您必须手动承诺。

s3.getObject(name).promise();

【讨论】:

  • 真的很喜欢.promise
猜你喜欢
  • 2022-01-17
  • 2018-10-04
  • 2020-07-10
  • 2019-07-17
  • 2021-10-29
  • 2019-02-03
  • 1970-01-01
  • 2019-05-26
  • 2021-08-18
相关资源
最近更新 更多