Why does the first method of promisifying work and not the second one?

和自甴很熟 提交于 2019-12-23 06:22:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!