Cannot partially apply lodash to function created with bluebird promisifyAll

The code below takes all the methods in the lib object and promises them. Then I can use the callback style function as a promise that works. Then I use _.partial to provide the function and arguments, this returns the function. When I call this function, it throws an error instead of wrapping the function. I have a whole group of tests here that show that this behavior only happens with functions generated using promisifyAll . What is the problem here and how can I fix it?

 var Promise = require("bluebird") var _ = require("lodash") var lib = {} lib.dummy = function(path, encoding, cb){ return cb(null, "file content here") } Promise.promisifyAll(lib) lib.dummyAsync("path/hello.txt", "utf8").then(function(text){ console.log(text) // => "file content here" }) var readFile = _.partial(lib.dummyAsync, "path/hello.txt", "utf8") readFile() // throws error 

He throws

 Unhandled rejection TypeError: Cannot read property 'apply' of undefined at tryCatcher (/Users/thomas/Desktop/project/node_modules/bluebird/js/main/util.js:26:22) at ret (eval at <anonymous> (/Users/thomas/Desktop/project/node_modules/bluebird/js/main/promisify.js:163:12), <anonymous>:11:39) at wrapper (/Users/thomas/Desktop/project/node_modules/lodash/index.js:3592:19) at Object.<anonymous> (/Users/thomas/Desktop/project/issue.js:18:1) at Module._compile (module.js:426:26) at Object.Module._extensions..js (module.js:444:10) at Module.load (module.js:351:32) at Function.Module._load (module.js:306:12) at Function.Module.runMain (module.js:467:10) at startup (node.js:117:18) at node.js:946:3 

While this works great.

 var dummyPromise = function(path, encoding){ return Promise.resolve("file content here") } var readFile = _.partial(dummyPromise, "path/hello.txt", "utf8") readFile().then(function(text){ console.log(text) // => "file content here" }) 
0
source share
2 answers

Copy response from tracker :

The _.partial problem _.partial not support the value of this , which is required when you promisifyAll . You can either use promisify or use _.bind , which is the appropriate lodash method.

 var o = {}; o.dummy = function(path, encoding, cb){ return cb(null, "file content here " + path + " " +encoding); } Promise.promisifyAll(o); o.dummyAsync("a","b").then(function(data){ console.log("HI", data); }); // and not `_.partial` var part = _.bind(o.dummyAsync, o, "a1", "b2"); part().then(function(data){ console.log("Hi2", data); }); 

http://jsfiddle.net/hczmb2kx/

+4
source

promisifyAll creates methods that expect a call in the original instance (since it calls the original .dummy method), but partial does not bind the functions you pass, so you get this . You can use either readFile.call(lib) or _.partial(lib.dummyAsync.bind(lib), …) , or just lib.dummyAsync.bind(lib, …) .

+1
source

All Articles