Manish Manish -4 years ago 85
Javascript Question

AWS Javascript SDK with Promises

I am trying to use AWS Javascript SDK for accessing S3. I am using the Promises with 'Q' library. However it is not working.
I have set the Q dependency also.

var Q = require('q');
AWS.config.setPromisesDependency(Q);


Here's the code I have:

var listBucketPromise = s3.listBuckets().promise();
listBucketPromise.then(
function (response) {
console.log(" response = " + response );
} ,
function (error) {
console.log(" error = " + error);
}
);


This shows on console :

response = function (resolve, reject) {
self.on('complete', function(resp) {
if (resp.error) {
reject(resp.error);
} else {
// define $response property so that it is not enumberable
// this prevents circular reference errors when stringifying the JSON object
resolve(Object.defineProperty(
resp.data || {},
'$response',
{value: resp}
));
}
});
self.runTo();
}


I have a valid s3 client set correctly. The callback format works:

s3.listBuckets(function (err, data) {
console.log(data);
});


Why is the promise code not working ?

Answer Source

You need to pass a Promise constructor to setPromisesDependency. The Q function that you used does not expect a callback, when called with the typical promise executor callback it just returned a promise fulfilled with that function value.

You can use Q.Promise instead, which also is documented in this blog post's example:

// Use Q implementation of Promise
AWS.config.setPromisesDependency(require('Q').Promise);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download