for循环不会以猫鼬调用的方式同步循环

时间:2019-06-16 14:29:15

标签: node.js mongoose async-await

我必须遍历用户列表,然后在mongo db中查找该情况下是否存在该记录,否则请跳过该记录

我尝试了async和await,我无法使用回调,因为我需要等到每次迭代完成

我看到调用甚至在之前的迭代完成之前就触发了。我需要同步它,因为我需要检查文档是否已经存在。

async function excelProcessing(res) {
  {
    for (index = 0; index < jsonData.length; index++) {
      await excelProcessingStep2(jsonData[index]);
    }

    res.send("done")
  }

  async function excelProcessingStep2(item) {
    subRoleData = JSON.parse(JSON.stringify(item))

    await collection.findOne({
      "$and": findCritList
    }, {
      "users": 1
    }, function(err, result) {
      //console.log(result)
      // console.log(item["No"],item["Sub Role Name"])
      if (err) {
        //console.log("Error")
      }
      if (result == null) {
        collection.create(newSubRoleDoc);

        // //Insert into Audit
        collectionAudit.create(newSubRoleDoc);
      }

      if (result) {
        console.log("Already Exists")
      }
    })
  }

0 个答案:

没有答案