问题描述
下面的代码采用对象lib
的所有方法并对其进行赋值。
然后,我可以使用回调样式函数作为Promise,它可以工作。
然后我使用_.partial
提供函数和参数,这将返回一个函数。
当我调用该函数时,它将引发错误而不是包装该函数。
我了大量测试,表明此行为仅发生在由promisifyAll
生成的promisifyAll
。
这是什么问题,如何解决?
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
扔
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
而这完全正常。
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"
})
1楼
Benjamin Gruenbaum
4
已采纳
2015-07-26 17:14:30
复制答案:
问题是_.partial
不会保留promisifyAll
时所需的this
值。
您可以改用promisify
,也可以使用_.bind
这是适当的lodash方法)。
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);
});
2楼
Bergi
1
2015-07-26 17:14:23
promisifyAll
确实会创建期望在原始实例上调用的方法(因为它确实会调用原始的.dummy
方法),但是partial
不绑定您传入的函数,因此您会遇到this
错误。
您可以使用readFile.call(lib)
或_.partial(lib.dummyAsync.bind(lib), …)
或仅使用lib.dummyAsync.bind(lib, …)
。