user605331
user605331

Reputation: 3788

Bluebird promisify on function with return value

I'd like to use Bluebird's promisify function on an AWS putItem function. Notice from the docs that it returns an AWS.Request object. I am not interested in that object and ideally I would just call db.putItem({...}); and get a Promise back. Is this possible? When I tried it, the promisify'd function still returns an AWS.Request object, which I suppose is reasonable, it's just not what I want in this case.

For the time being I am just creating a Promise object and manually mapping the success and error data to the resolve/reject promise functions, but it feels like I'm writing unnecessary boilerplate code, since aside from that return value, the putItem function (and may of the other functions) seems well suited for promisify.

As requested, here are the relevant parts of the code:

//datastore.js

var AWS = require('aws-sdk');

var sharedDB;

if (!sharedDB) {
    AWS.config.update({accessKeyId: 'akid', secretAccessKey: 'secret', region: "us-west-2"});
    sharedDB = new AWS.DynamoDB();
    sharedDB.setEndpoint("http://localhost:8000");
    Promise.promisify(sharedDB.putItem); 
}

module.exports.sharedDB = sharedDB;

//user.js

var db = require('../datastore/dynamoDBConnection').sharedDB;
var Promise = require("bluebird");


function User() {
var user = this;
...

user.save = function () {
        var params = {
            Item: {
                username: {S: 'test'},
                passwordHash: {S: 'test'}
            },
            TableName: 'users',
            Expected: {
                username: {Exists: false}
            }
        };
        return db.putItem(params); //this is where I would like have a Promise returned.  Instead I get an AWS.Request object.
}
...
}

Upvotes: 2

Views: 5632

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276406

Update

You're using Promisify wrong, it returns the promisified function.

var putItemAsync = Promise.promisify(sharedDB.putItem); 

And use putItemAsync. Also, you should only call promisify once and cache it.


PutItem takes a callback, but it resolves with a stream, so promisifying it is a little tricker than usual.

return new Promise(function(resolve,reject){
    dynamoDB.putItem(
    {"TableName":"Table1",
        "Item":{
            "Color":{"S":"white"},
            "Name":{"S":"fancy vase"},
            "Weight":{"N":"2"}
        }
    }, function(result) {
        var wholeResult = [];
        result.on('data', function(chunk){
            wholeResult.push(chunk);
        });
        result.on('end', function(){ resolve(Buffer.concat(wholeResult))});
        result.on('error', function(e){ reject(new Error(e)); });
    });
});

Upvotes: 4

Related Questions