What is wrong with this code that promisify a function?

℡╲_俬逩灬. 提交于 2019-12-10 12:19:28

问题


This function does not return a promise.

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?


回答1:


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)


来源:https://stackoverflow.com/questions/33579870/what-is-wrong-with-this-code-that-promisify-a-function

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