在Typescript中如何与类型安全性绑定时赋函数?

Tom*_*Tom 1 javascript amazon-s3 node.js typescript

考虑以下承诺:

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

这可以正常工作,除了会出现错误,TypeError: this.makeRequest is not a function因为s3.getObject现在绑定到错误的this作用域。但是,这:

const getObject = promisify<S3.GetObjectRequest, S3.GetObjectOutput>(
  s3.getObject.bind(s3)
)
Run Code Online (Sandbox Code Playgroud)

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

那么,如何getObject在Typescript中实现s3之类的内容呢?

Exp*_*lls 5

您可以传递另一个s3.getObject()无需绑定的函数。使用箭头功能,您只需很少的附加代码即可完成此操作。

const getObject = promisify<S3.GetObjectRequest, S3.GetObjectOutput>(
  name => s3.getObject(name)
)
Run Code Online (Sandbox Code Playgroud)

但是,AWS开发工具包操作员函数通常具有一种.promise返回承诺的方法,而无需您手动进行承诺。

s3.getObject(name).promise();
Run Code Online (Sandbox Code Playgroud)

  • 真的很喜欢`.promise`! (2认同)