Promisifying a function with Bluebird

孤人 提交于 2019-12-25 05:50:54

问题


I am new to javascript asynchronous concepts and come from a C++ background. Recently, I realize that some of my functions do not work because they do not return promises.

For example, this function;

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;
    });
}

If I try to assign a variable based on the function's return value, I get undefined.

var alerts_obj = get_json(testData);

How can get_json() be modified to return promises? I would like to use Bluebird. I am reading up on promises but it is rather overwhelming at the moment for a beginner.


回答1:


If you're using bluebird, you can simply use Promisification with promisifyAll():

var Promise = require('bluebird');
var Converter = Promise.promisifyAll(require("csvtojson").Converter);

And make your function

function get_json(cvs_file_location) {
    var data=fs.readFileSync(cvs_file_location).toString();

    return new Converter().fromString(data)
        .then(function(jsonObj){
            var json_csv = clone_obj(jsonObj);
            console.log(json_csv);
            return json_csv;
    })
        .catch(function(err) {
            console.log("error msg: " + err);
            return null;
    });        
}

Edit for your second comment:

You would do something like this to get the value:

get_json(cvs_file_location).then(function(val) { console.log(val) }

But you can't assign it to a variable directly, as it is asynchronous. See this question and answer for more insights here: How to return value from an asynchronous callback function?



来源:https://stackoverflow.com/questions/33577646/promisifying-a-function-with-bluebird

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