问题
This is a follow-up question to What is wrong with this code that promisify a function?
Method 1 works;
var Converter = require('csvtojson').Converter;
Promise.promisifyAll(Converter.prototype);
var converter = new Converter();
Method 2 does not work;
var Converter = require('csvtojson').Converter;
var converter = Promise.promisifyAll(Converter.prototype);
Why does method 1 work and not method 2?
回答1:
Promise.promisifyAll(obj)
returns obj, therefore ...
Promise.promisifyAll(Converter.prototype)
... returns Converter.prototype, not Converter therefore ...
var converter = Promise.promisifyAll(Converter.prototype);
... will assign Converter.prototype to converter.
In order to promisify the prototype and assign an instance of Converter, you should (realistically) write two statements (ie Method 1) :
Promise.promisifyAll(Converter.prototype);
var converter = new Converter();
You could write the single line ...
var converter = new (Promise.promisifyAll(Converter.prototype).constructor);
... though it's less readable.
回答2:
On re-examination of the documentation https://www.npmjs.com/package/csvtojson, Convertor is a constructor. It has to be used with new in front.
来源:https://stackoverflow.com/questions/33582172/why-does-the-first-method-of-promisifying-work-and-not-the-second-one