使用来自不同异步函数的响应创建一个json对象

create a json object with responses from different async functions

本文关键字:创建 对象 json 一个 响应 函数 异步      更新时间:2023-09-26

我的目标是从一段文本中创建一个JSON对象,然后将其作为文档插入MongoDB。我正在使用nodejs,并希望采用异步方法。

我的JSON有这样的参数

{
   height:height,
   weight:weight
}

我的逻辑是这个

创建一个带有异步函数的模块,该模块解析文本并使用regex提取权重和高度。

但是,我该如何将这些函数的所有响应组合成一个可以一次导入的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
   }); 
}

我发现async令人困惑,在上面的例子中,我不确定有两件事

  1. 如果不等待来自前两个功能(重量、高度)的数据,combine_json就不会运行吗

  2. 处理此类案件的最佳做法是什么?我应该只使用sync函数,从上到下等待每个函数完成它的任务,然后运行最后一个函数,还是可以利用async?

等待两个独立异步函数结果的最简单方法是使用promise和Promise.all。为此,我们假设get_heightget_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以获取文档和详细信息。

如果您对Promises一无所知,您首先应该知道回调是如何工作的。如果您不想要Promise.all()的优雅解决方案,而只想让代码正常工作,则需要嵌套函数。当你在get_height回调时,你应该调用get_weight,当你在get_weight回调时,同样你应该调用combine_json()。唯一的问题是您必须等待get_height才能调用get_weight。这是通过Promise.al()解决的。

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

Promises是您的最佳选择,但如果您出于某种原因不想使用它们,并且更喜欢回调风格,那么

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可以更好地处理这种情况。