问题描述
此函数不返回承诺。
它使用csvtojson模块。
It uses the csvtojson module.https://www.npmjs.com/package/csvtojson
var CSVConverter=require("csvtojson").Converter;
function get_json(cvs_file_location)
{
var data=fs.readFileSync(cvs_file_location).toString();
var csvConverter=new CSVConverter();
csvConverter.fromString(data,function(err,jsonObj){
if (err){
console.log("error msg: " + err);
return null;
}
var json_csv = clone_obj(jsonObj);
console.log(json_csv);
return json_csv;
});
}
我想将其转换为返回承诺的一个。这就是我写的;
I would like to convert it into one that returns a promise. This is what I wrote;
var Promise = require('bluebird');
var Converter = Promise.promisifyAll(require("csvtojson").Converter);
function get_json(cvs_file_location)
{
var data=fs.readFileSync(cvs_file_location).toString();
return new Converter().fromStringAsync(data)
.then(function(csvString){
var json_csv = clone_obj(csvString);
console.log(json_csv);
return json_csv;
})
.catch(function(cb) {
console.log("error msg: " + cb);
return null;
});
}
不幸的是,它不起作用。错误消息如下所示;
Unfortunately, it does not work. The error message looks like this;
return new Converter().fromStringAsync(data)
^ TypeError: (intermediate value).fromStringAsync is not a function
代码有什么问题?或者是否有另一种方法来编写代码来返回一个承诺?
What is wrong with the code? Or is there another way to write the code to return a promise?
推荐答案
你必须宣传原型
的转换器
因为它是构造函数。常规 var Converter = Promise.promisifyAll(require('csvtojson')。Converter));
如果转换器
将会有效对象直接具有要被保护的功能(与大多数API一样)。
You have to promisify the prototype
of Converter
because of it being a constructor. Regular var Converter = Promise.promisifyAll(require('csvtojson').Converter));
would work if the Converter
object directly had the functions to be promisified (as is the case with most APIs).
var fs = require('fs');
var Promise = require('bluebird');
var Converter = require('csvtojson').Converter;
Promise.promisifyAll(Converter.prototype);
var converter = new Converter();
converter.fromStringAsync(fs.readFileSync('foo.csv', 'utf8'))
.then(console.log)
这篇关于宣传这个功能的代码有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!