如何在JS循环内使用猫鼬功能

时间:2019-06-28 03:45:41

标签: node.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);
          }
        }
      );
    }
  });
};

2 个答案:

答案 0 :(得分:0)

您可以将 Promise asyncawait

一起使用
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];
      const { order, err } = await findOrder(eachBody);
      if (err) {
        res.send(err);
      }
      console.log("Order found:", order._id);
    }
  });
};

function findOrder() {
  return new Promise(resolve => {
    Order.findOne(
      {
        order_id: eachBody.order_id
      },
      (err, exOrder) => {
        resolve({
          order: exOrder,
          err
        });
      }
    );
  });
}

如果您想获取有关异步/等待和承诺的更多详细信息,并可能异步执行多次请求,建议您检查一下 this article

答案 1 :(得分:0)

检查此代码,使用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);
      }
    }
  });
};