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?
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With