当前位置: 代码迷 >> JavaScript >> 无法将lodash部分应用于蓝鸟promisifyAll创建的函数
  详细解决方案

无法将lodash部分应用于蓝鸟promisifyAll创建的函数

热度:75   发布时间:2023-06-05 09:43:14.0

下面的代码采用对象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"
})

复制答案:

问题是_.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); 
});

promisifyAll确实会创建期望在原始实例上调用的方法(因为它确实会调用原始的.dummy方法),但是partial不绑定您传入的函数,因此您会遇到this错误。 您可以使用readFile.call(lib)_.partial(lib.dummyAsync.bind(lib), …)或仅使用lib.dummyAsync.bind(lib, …)