簡體   English   中英

在Typescript中如何與類型安全性綁定時賦函數?

[英]In Typescript how to promisify a function while binding with type safety?

考慮以下承諾:

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錯誤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的東西呢?

您可以傳遞另一個調用s3.getObject()函數,而不必綁定它。 使用箭頭功能,您只需很少的附加代碼即可完成此操作。

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

但是,AWS開發工具包操作員函數通常具有一個.promise方法,該方法返回一個promise,而無需您手動進行承諾。

s3.getObject(name).promise();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM