【问题标题】:Mongoose async requests managmentMongoose 异步请求管理
【发布时间】:2018-05-14 16:12:04
【问题描述】:

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

通过使用 map、for/forEach 进行了尝试,但由于 mongoose 请求是异步的,因此没有任何效果。

不太习惯这种代码,尝试了这么多,感觉有点失落。

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

仅供参考,无需担心加载模板、连接到 mongo 等,因为其他一切正常。

这是我得到的最接近预期结果的结果,但是当我尝试“console.log(cond[c​​]);/console.log(info); " (cond[c​​] 和 info 为 null 且未定义)

这个函数也需要准备好递归,因为我打算将子块放在 bloc 对象的“内容”属性中。

非常感谢你们的时间。

// 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' }]
});

【问题讨论】:

  • 你可以使用新的 Node.js 还是你被一些旧版本卡住了?

标签: node.js mongoose async-await


【解决方案1】:

使用承诺并在小函数中破坏您的代码:

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

【讨论】:

  • 这正是我所需要的,非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-11
  • 1970-01-01
  • 2018-08-21
  • 2012-05-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多