Cody
Cody

Reputation: 1208

Error turning Amazon S3 function into promises using when/node

I'm trying to lift an AWS S3 async function, and running into a weird error. Given the following code,

var s3 = new AWS.S3();
var when = require('when');
var nodefn = require('when/node');

var getObjectP = nodefn.lift(s3.getObject);

getObjectP({
    Bucket: 'bucket_name',
    Key: 'key_name'
})
.then(function(data) {
    ...
}, function(err) {
    ...
});

I get this error,

Object #<Object> has no method 'makeRequest'

Here's what the getObject looks like normally (it works fine when I use callbacks instead of promises):

s3.getObject({ ... }, function(err, data) {
    ...
});

Am I misusing nodefn.lift? It seems pretty straight-forward. Here's the docs for anyone interested. https://github.com/cujojs/when/blob/master/docs/api.md#nodelift

Upvotes: 7

Views: 4782

Answers (2)

oyelaking
oyelaking

Reputation: 542

AWS Javascript SDK now supports Promises(https://aws.amazon.com/blogs/developer/support-for-promises-in-the-sdk/). You can either use the built-in Promise implementation(if you are using ES6) or you can use one of the several Javascript Promise libraries available.

Using When Promise Library

var AWS = require('aws-sdk');
AWS.config.setPromisesDependency(require('when'));
var s3 = new AWS.S3();

s3.getObject({
    Bucket: 'bucket_name',
    Key: 'key_name'
}).promise()
.then(function(data) {
    ...
}, function(err) {
    ...
});

Using ES6 built-in Promise Library

var AWS = require('aws-sdk');
var s3 = new AWS.S3();

s3.getObject({
    Bucket: 'bucket_name',
    Key: 'key_name'
}).promise()
.then(function(data) {
    ...
}, function(err) {
    ...
});

So the difference between both is one line.

Upvotes: 8

Bergi
Bergi

Reputation: 664599

Probable the method has the wrong context, as it is not called as a method. Try to bind it:

var getObjectP = nodefn.lift(s3.getObject.bind(s3));

Upvotes: 20

Related Questions