简体   繁体   English

使用Bluebird保证功能

[英]Promisifying a function with Bluebird

I am new to javascript asynchronous concepts and come from a C++ background. 我是javascript异步概念的新手,来自C ++背景。 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? 如何修改get_json()以返回诺言? I would like to use Bluebird. 我想使用蓝鸟。 I am reading up on promises but it is rather overwhelming at the moment for a beginner. 我正在阅读诺言,但对于初学者而言,这是相当令人头疼的。

If you're using bluebird, you can simply use Promisification with promisifyAll() : 如果您使用的是bluebird,则可以简单地将PromisificationpromisifyAll()结合使用

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? 有关更多信息,请参见以下问题和解答: 如何从异步回调函数返回值?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM