我的目标是从一段文本创建一个JSON对象,然后我可以将其作为文档插入到MongoDB中。我使用nodejs并希望采用异步方法。
我的JSON有像这样的参数
{
height:height,
weight:weight
}
我的逻辑就是这个
使用异步函数创建一个模块,该函数解析文本并使用正则表达式提取权重和高度。
但是,我如何将这些函数的所有响应组合成一个我可以一次导入的JSON?
我在想这样的事情
var get_height = require().height;
var get_weight = require().weight;
exports.contr = function(){
var height,
weight;
get_height(text, function(err, res){
if(err)
throw(err)
height=res;
});
get_weight(text, function(err, res){
if(err)
throw(err)
weight=res;
});
//All other async functions
combine_json(height, weight, ... , function(err, res){
if(err)
throw(err);
console.log(res); //the json was successfully inserted into mongoDB
});
}
我觉得异步混乱,在上面的例子中,我不确定两件事
在没有等待前两个函数(体重,身高)的数据的情况下运行combine_json
处理此类案件的最佳做法是什么?我应该只使用同步功能并从上到下等待每个人做其事情,然后运行最后一个或我可以利用异步?
答案 0 :(得分:1)
等待两个独立异步函数结果的最简单方法是使用promises和Promise.all
。为此,我们假设get_height
和get_weight
返回Promise
,可以这样使用:
get_height().then(function (height) { console.log(height); });
然后将两个承诺结合起来是微不足道的:
Promise.all([get_height(), get_weight()]).then(function (results) {
combine_json(results[0], results[1]);
});
有关文档和详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise。
答案 1 :(得分:0)
如果你对Promises一无所知,首先应该知道回调是如何工作的。如果您不希望使用Promise.all()
的优雅解决方案并且只是希望代码正常工作,则需要嵌套函数。当你在get_height
回调内时,你应该拨打get_weight
,当你在get_weight
回调时,你应该拨打combine_json()
。唯一的问题是您必须等待get_height
致电get_weight
。这可以通过Promise.all()来解决。
get_height(text, function(err, height){
if(err)
throw(err);
get_weight(text, function(err, weight){
if(err)
throw(err);
//All other async functions
combine_json(height, weight, ... , function(err, res){
if(err)
throw(err);
console.log(res); //the json was successfully inserted into mongoDB
});
});
});
答案 2 :(得分:0)
承诺是你最好的选择,但如果你因为某种原因不想使用它们而更喜欢回调风格,那么
function get_height_and_weight(text, callback) {
var have_height = false;
var have_weight = false;
var result = {};
get_height(text, function(err, height) {
if (err) callback(err);
have_height = true;
result.height = height;
if (have_weight) callback(null, result);
});
get_weight(text, function(err, weight) {
if (err) callback(err);
have_weight = true;
result.weight = weight;
if (have_height) callback(null, result);
});
}
这是并行异步调用案例的一个特例,async.parallel
可以更好地处理。