使用Bluebird保证功能 [英] Promisifying a function with Bluebird
问题描述
我是javascript异步概念的新手,来自C ++背景.最近,我意识到我的某些功能不起作用,因为它们不返回承诺.
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.
例如,此功能;
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);
如何修改get_json()
以返回承诺?我想使用蓝鸟.我正在阅读诺言,但对于初学者而言,这真是令人不知所措.
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.
推荐答案
如果您使用的是bluebird,则只需使用承诺与 promisifyAll():
If you're using bluebird, you can simply use Promisification with promisifyAll():
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().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;
});
}
编辑您的第二条评论:
您将执行以下操作以获取值:
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?
这篇关于使用Bluebird保证功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!