node.js - Bluebird promisify on function with return value -
i'd use bluebird's promisify function on aws putitem function. notice docs returns aws.request object. not interested in object , ideally call db.putitem({...}); , promise back. possible? when tried it, promisify'd function still returns aws.request object, suppose reasonable, it's not want in case.
for time being creating promise object , manually mapping success , error data resolve/reject promise functions, feels i'm writing unnecessary boilerplate code, since aside return value, putitem function (and may of other functions) seems suited promisify.
as requested, here relevant parts of 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 have promise returned. instead aws.request object. } ... }
update
you're using promisify wrong, returns promisified function.
var putitemasync = promise.promisify(shareddb.putitem);
and use putitemasync
. also, should call promisify once , cache it.
putitem takes callback, resolves stream, promisifying little tricker 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)); }); }); });
Comments
Post a Comment