当省略参数时,我无法使用Bluebird library的promisifyAll
函数来处理ES2015类的对象实例方法。我正在使用Node 7.8.0。这是一些示例代码:
// dog.js
class Dog {
constructor(opts) {
this.name = opts.name || 'Fido';
}
fetchBone(bone, callback) {
console.log('fetching the bone');
callback(null, 'got it');
}
}
exports = module.exports = Dog;
假设骨骼是fetchBone
的可选参数。当我通过它时,一切都很好。
> var Dog = require('./dog');
> Promise = require('bluebird');
> Promise.promisifyAll(Dog); // omitting this line doesn't help
> Promise.promisifyAll(Dog.prototype);
> var puppy = new Dog();
> puppy.fetchBoneAsync('juicy bone')
.then(result => console.log('from promise:', result))
.catch(err => console.error('failure:', err));
fetching the bone
Promise {
_bitField: 0,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_promise0: undefined,
_receiver0: undefined }
> from promise: got it
当我没有传入骨头时失败。
> puppy.fetchBoneAsync()
.then(result => console.log('from promise:', result))
.catch(err => console.error('failure:', err));
fetching the bone
Promise {
_bitField: 0,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_promise0: undefined,
_receiver0: undefined }
> failure: TypeError: callback is not a function
at Dog.fetchBone (dog.js:8:5)
at Dog.tryCatcher (node_modules/bluebird/js/release/util.js:16:23)
at Dog.ret [as fetchBoneAsync] (eval at makeNodePromisifiedEval (node_modules/bluebird/js/release/promisify.js:184:12), <anonymous>:14:23)
at repl:1:7
at ContextifyScript.Script.runInThisContext (vm.js:23:33)
at REPLServer.defaultEval (repl.js:339:29)
at bound (domain.js:280:14)
at REPLServer.runBound [as eval] (domain.js:293:12)
at REPLServer.onLine (repl.js:536:10)
at emitOne (events.js:101:20)
at REPLServer.emit (events.js:191:7)
at REPLServer.Interface._onLine (readline.js:241:10)
at REPLServer.Interface._line (readline.js:590:8)
at REPLServer.Interface._ttyWrite (readline.js:869:14)
at REPLServer.self._ttyWrite (repl.js:609:7)
at ReadStream.onkeypress (readline.js:120:10)
奇怪的是,如果我传入undefined
骨骼,它就会起作用。
> puppy.fetchBoneAsync(undefined)
.then(result => console.log('from promise:', result))
.catch(err => console.error('failure:', err));
fetching the bone
Promise {
_bitField: 0,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_promise0: undefined,
_receiver0: undefined }
> from promise: got it
有人知道这里发生了什么吗?
答案 0 :(得分:1)
是的,这是正确的行为。承诺映射到原始函数。所以fetchBone()
在第一个调用中接收两个参数,在第二个示例中接收一个。
这意味着在第二个示例中,调用fetchBone()
时callback
未定义且bone
本身是由promisification创建的回调函数来处理promise本身。