Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Consider the following promisification:

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
)

This works fine, except that you'll get errors like TypeError: this.makeRequest is not a function because s3.getObject is now bound to the wrong this scope. However, this:

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

Destroys type safety and will error out: Unsafe use of expression of type 'any'. (assuming you use strict mode).

So how can I promisify something like s3's getObject in Typescript?

like image 830
Tom Avatar asked Aug 16 '18 18:08

Tom


People also ask

What is the purpose of the util Promisify () function?

The util. promisify() method basically takes a function as an input that follows the common Node. js callback style, i.e., with a (err, value) and returns a version of the same that returns a promise instead of a callback.


1 Answers

You can pass another function that calls s3.getObject() without having to bind it. Using arrow functions you can do this with very little additional code.

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

However, the AWS SDK operator functions generally have a .promise method that returns a promise rather than you having to promisify manually.

s3.getObject(name).promise();
like image 146
Explosion Pills Avatar answered Oct 28 '22 03:10

Explosion Pills