Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 323
Cody Avatar asked Jul 10 '14 23:07

Cody


People also ask

Does S3 getObject return a promise?

2.1. The first change is that the getObject method will return a Promise . In version 2, the getObject method returns an object, and we had to call the promise() method, which resolves to the S3 response.

How do I create a promise in node JS?

Promises are generally created by calling a Promise constructor, which accepts a single callback function as an argument. The callback function, also known as the executor function, is executed immediately after a promise is created.

Is an AWS request a promise?

The AWS. Request. promise method provides a way to call a service operation and manage asynchronous flow instead of using callbacks.


2 Answers

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));
like image 181
Bergi Avatar answered Nov 15 '22 08:11

Bergi


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.

like image 24
king Avatar answered Nov 15 '22 08:11

king