繁体   English   中英

猫鼬异步请求管理

[英]Mongoose async requests managment

我实际上正在尝试使用javascript中的猫鼬将mongodb引用转换为那些引用的文档值(info.value)。

通过使用map,for / forEach进行了尝试,由于猫鼬请求是异步的,因此该工作没有任何作用。

我不太习惯这种代码,在尝试了所有这些东西之后,我感到有些迷失。

也许有人想通过看下面的代码给我一些提示。

仅提供信息,无需担心加载模板,连接到mongo的问题,因为其他一切都很好。

这是我最接近预期结果的方法,但是当我尝试“ console.log(cond [c]); / console.log(info); ”(cond [c]和info为null时,它仍然抛出错误和未定义)

因为我计划将子块放在块对象的“内容”属性中,所以还需要准备该函数以递归。

非常感谢您的宝贵时间。

// Input condition
"H1Vf3KTef || false"

// Expected result
"1 || false"

// Buggy Function
var execIfBlock = function recursExec (query, callback) {
  IfBlockModel.findOne(query, function(err, ifBlock) {
    if (!err) {
      var cond = ifBlock.condition.split(" ");
      //console.log('Block : ' + ifBlock);
      //console.log('Condition : ' + cond);
      var calls = new Array();
      for (var c = 0, len = cond.length; c < len; c++) {
        if (shortId.isValid(cond[c])) {
          calls.push(function() {
            InfoModel.findOne({ _id: cond[c] }, function(err, info) {
              console.log(cond[c]);
              console.log(info);
              cond[c] = info.value;
            });
          });
        }
      }
      async.parallel(calls, function(err, result) {
        console.log(result);
        // Do some job using the final expected result : "1 || false"
      });
    }
  });
};

// Info template
{
  "_id": "H1Vf3KTef",
  "value": "1"
}

// Bloc template
{
  "_id": "rkRBtLTef",
  "content": [],
  "condition": "H1Vf3KTef || false"
}

// Info schema
var InfoSchema = new Schema({
  _id: { type: String, unique: true, required: true, default: shortId.generate },
  value: { type: String, default: "0" }
});

// Bloc schema
var IfBlockSchema = new Schema({
  _id: { type: String, unique: true, required: true, default: shortId.generate },
  condition: { type: String, required: true, default: true },
  content: [{ type: String, required: true, default: '', ref: 'block' }]
});

使用Promise并在一些小函数中破坏代码:

var execIfBlock = function recursExec(query, callback) {
    IfBlockModel.findOne(query, function (err, ifBlock) {
        if (!err) {
            var cond = ifBlock.condition.split(" ");

            updateMultipeInfo(cond)
                .then(values => {
                    console.log(values) // [values1, values ,...]
                });
        }
    });
};


function updateMultipeInfo(cond){
    return Promise.all(cond.map(updateInfo))
}

function updateInfo(id){
    if (shortId.isValid(id)) {
        return InfoModel
            .findOne({ _id: id })
            .then(info => info.value);
    } else {
        return Promise.reject("invalid id");
    }
}

暂无
暂无

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

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