如何在节点表示中循环调用服务?

时间:2019-04-25 13:22:52

标签: javascript node.js async-await

我试图在一个循环中的节点表示中调用服务。但是问题在于,在调用所有服务之前,其余代码将被执行。

我用Promise尝试了一些选项,异步/等待,但是它们没有用。 基本上,我需要以同步方式调用服务。

我在JSON存根中创建了2个模拟服务。在第一个服务响应中,我将获得一系列车辆。一旦知道了这一点,就需要通过调用另一个服务来更新每个数组中的另一个值。

这里我遇到的问题是第二服务没有被同步调用。

const express = require('express');
const request = require("request");
const router = express.Router();
router.get('/make', (req, res) => {
    var options = {
      headers: {
        'Content-Type': 'application/json',
        'JsonStub-User-Key': 'ddc159a0-5aa8-4a38-a0f1-913e4d768b56',
        'JsonStub-Project-Key': '34ba28a9-471c-435d-ab61-b7732c9583c6'
      },
        method: "GET",
        json: true,
        strictSSL : false,
        url: `http://jsonstub.com/vehicle/make`
      };
      request(options, function(error, response, body) {
        if (body){
          checkModelType(body);
          res.status(200).json(body).end();
        } else {
          console.log("REST Request timeout: ", JSON.stringify(error));
          res.status(400).json('Error').end();
        }
      });
});

function checkModelType(response){
  let vehicleList = response.vehicleList;
  console.log("--->"+vehicleList.length);
  for(var i = 0;i<vehicleList.length;++i){
   const modelType = findModel();
   vehicleList[i].modelType = modelType;
  }
  console.log("Updated Vehicle List:"+JSON.stringify(vehicleList));
}

const findModel = () =>{
  var options = {
    headers: {
      'Content-Type': 'application/json',
      'JsonStub-User-Key': 'ddc159a0-5aa8-4a38-a0f1-913e4d768b56',
      'JsonStub-Project-Key': '34ba28a9-471c-435d-ab61-b7732c9583c6'
    },
      method: "GET",
      json: true,
      strictSSL : false,
      url: `http://jsonstub.com/vehicle/details`
    };

    request(options, function(error, response, body) {
      if (body){
        console.log("Model Type-->"+body.output.modelType);
        return body.output.modelType;
      } else {
        console.log("REST Request timeout: ", JSON.stringify(error));
      }
    });
}

module.exports = router;


Response :
-----------

PS F:\workSpace_Node\TestApp> node app.js
server running at 9086
--->4
Updated Vehicle List:[{"make":"Audi","model":"A3","vin":"QVFCFQT7894563214"},{"make":"Audi","model":"A4","vin":"ASECFQT7894563214"},{"make":"Audi","model":"Q5","vin":"QWECFQT7894993214"}]
Model Type-->SD
Model Type-->SD
Model Type-->SD


Expected result :
[{"make":"Audi","model":"A3","modelType":"SD", "vin":"QVFCFQT7894563214"},{"make":"Audi","model":"A4","modelType":"SD","vin":"ASECFQT7894563214"}]

1 个答案:

答案 0 :(得分:0)

您可以切换到请求承诺库而不是请求,然后执行一些async \ await:

const express = require('express');
const request = require('request-promise'); // switched library
const router = express.Router();
router.get('/make', async (req, res) => {
    var options = {
      headers: {
        'Content-Type': 'application/json',
        'JsonStub-User-Key': 'ddc159a0-5aa8-4a38-a0f1-913e4d768b56',
        'JsonStub-Project-Key': '34ba28a9-471c-435d-ab61-b7732c9583c6'
      },
        method: "GET",
        json: true,
        strictSSL : false,
        url: `http://jsonstub.com/vehicle/make`
      };
      const body = await request(options);
      if (body) {
        await checkModelType(body);
        res.status(200).json(body).end();
      } else {
        console.log("REST Request timeout: ", JSON.stringify(error));
        res.status(400).json('Error').end();
      }
});

async function checkModelType(response){
  let vehicleList = response.vehicleList;
  console.log("--->"+vehicleList.length);
  for(var i = 0;i<vehicleList.length;++i){
    const modelType = await findModel();
    vehicleList[i].modelType = modelType;
  }
  console.log("Updated Vehicle List:"+JSON.stringify(vehicleList));
}

const findModel = async () =>{
  var options = {
    headers: {
      'Content-Type': 'application/json',
      'JsonStub-User-Key': 'ddc159a0-5aa8-4a38-a0f1-913e4d768b56',
      'JsonStub-Project-Key': '34ba28a9-471c-435d-ab61-b7732c9583c6'
    },
      method: "GET",
      json: true,
      strictSSL : false,
      url: `http://jsonstub.com/vehicle/details`
    };

    const body = await request(options);
    if (body){
      console.log("Model Type-->"+body.output.modelType);
      return body.output.modelType;
    } else {
      console.log("REST Request timeout: ", JSON.stringify(error));
    }
}

module.exports = router;

它将改变操作顺序:

--->4
Model Type-->SD
Model Type-->SD
Model Type-->SD
Model Type-->SD
Updated Vehicle List:[{"make":"Audi","model":"A3","vin":"QVFCFQT7894563214","modelType":"SD"},{"make":"Audi","model":"A4","vin":"ASECFQT7894563214","modelType":"SD"},{"make":"Audi","model":"Q7","modelType":"SD"},{"make":"Audi","model":"Q5","vin":"QWECFQT7894993214","modelType":"SD"}]