首页 > 解决方案 > 如何在 JS 的循环中使用猫鼬函数

问题描述

我正在使用“request-promise”模块从某些 API 获取数据。
这将数组值作为主体。
我想将该数组保存为 mongoDB 中的每个文档。
因此,我用'for'作为循环。
但是当我用 console.log 检查这个时,
我希望像下面这样。

Current i is : 0
orderFind
Current i is : 1
orderFind
Current i is : 2
orderFind
Current i is : 3
orderFind

然而它给了我

Current i is : 0
Current i is : 1
Current i is : 2
Current i is : 3
orderFind
orderFind
orderFind
orderFind

我试过异步,等待也。但是效果不好。。

exports.saveOrder = (req, res) => {
  rp({
    method: "GET",
    uri: "https://robot.com",
    json: true
  }).then(body => {
    for (let i = 0; i < body.length; i += 1) {
      console.log(`Current i is : ${i}`);
      const eachBody = body[i];

      Order.findOne(
        {
          order_id: eachBody.order_id
        },
        (err, exOrder) => {
          console.log("orderFind");
          if (err) {
            return res.send(err);
          }
        }
      );
    }
  });
};

标签: node.js

解决方案


检查此代码,使用async/await您可以解决问题

exports.saveOrder = (req, res) => {
  rp({
    method: "GET",
    uri: "https://robot.com",
    json: true
  }).then(async body => {
    for (let i = 0; i < body.length; i += 1) {
      console.log(`Current i is : ${i}`);
      const eachBody = body[i];
      try {
        const result = await Order.findOne({ order_id: eachBody.order_id });
        console.log(result);
      } catch (e) {
        return res.send(e);
      }
    }
  });
};


推荐阅读