0

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.

guagay_wk
  • 26,337
  • 54
  • 186
  • 295

1 Answers1

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?

Community
  • 1
  • 1
baao
  • 71,625
  • 17
  • 143
  • 203
  • Thanks! Upvoted. Looks promising indeed. Can I promisifyAll any node.js module? After promisifyAll, do I have to use this .then and .catch structure for every function that uses the module that has been promisifyAll? – guagay_wk Nov 07 '15 at 00:52
  • May I ask how do I use the new `get_json()` that returns a promise and assign it to a variable? – guagay_wk Nov 07 '15 at 00:53
  • 1
    You can promisifyAll most/many modules, see the first link I posted above on how to do that. Sometimes you would have to go with the prototype though. You don't have to use then and catch, though you should – baao Nov 07 '15 at 00:54
  • 1
    @user768421 I didn't use csv2json before, maybe you have to use `fromStringAsync()`... – baao Nov 07 '15 at 00:59
  • Selected your answer as the answer. You're most helpful! – guagay_wk Nov 07 '15 at 00:59