简体   繁体   English

需要使用node js在循环中调用两个API

[英]Need to call Two APIs In Loop using node js

I have an array of ssn number and I have two api list in which I need to pass ssn number as request json so I need to call both api inside ssn loop so I pass ssn to json request during call both api but code is not work properly both api call at a time simulteniously, Where I need to call both api one by one. I have an array of ssn number and I have two api list in which I need to pass ssn number as request json so I need to call both api inside ssn loop so I pass ssn to json request during call both api but code is not work正确地同时调用两个 api ,我需要一个一个调用两个 api 。

Both API details and code are as follow API 的详细信息和代码如下

My Code:我的代码:

let ssn = [460458524, 637625452, 453311896, 635285187, 455791630, 642348377, 463590491, 450730278, 641201851, 379965491];
async function getCRCDetails() {
  ssn.forEach(function (item) {
    if(item){
    let CBCOptions = {
      'method': 'POST',
      'url': 'https://loanboard.houstondirectauto.com/api/Report',
      'headers': {
        'Content-Type': 'application/json',
        'Cookie': 'ci_session=udmojmlc5tfl3epbrmtvgu6nao2f031p'
      },
      body: JSON.stringify({
        "token": loantoken,
        "action": "CBCReport",
        "variables": {
          ssn: item
        }
      })
    }
 request(CBCOptions, function (error, response) {
        console.log(item);
        console.log("CBCOPtion ", CBCOptions);
        if (error) throw new Error(error);
        result = (JSON.parse(response.body));
        console.log("Result =", result);
        CRCReport.push(result);
      })
 let EmployerInfoOptions = {
        'method': 'POST',
        'url': 'https://loanboard.houstondirectauto.com/api/Report',
        'headers': {
          'Content-Type': 'application/json',
          'Cookie': 'ci_session=udmojmlc5tfl3epbrmtvgu6nao2f031p'
        },
        body: JSON.stringify({
          "token": loantoken,
          "action": "getEmployerInfo",
          "variables": {
            ssn: item
          }
        })
      }
 request(EmployerInfoOptions, function (error, response) {
       console.log(response.body);

      })

}

Here I need to call API request one by one.Anyone Guide me please.这里我需要一一调用API请求。请大家指导一下。

In Node the request methods that you are using are asynchronous.在 Node 中,您使用的请求方法是异步的。 Meaning the runner (server) that runs the code does not wait for the request to finish and just continues to execute the next lines.这意味着运行代码的运行程序(服务器)不会等待请求完成,而是继续执行下一行。

One thing that you can do is,你可以做的一件事是,

request.post(params).on("response", function(response) {
//....Do stuff with your data you recieve
// Make the next call here
request.post(params).on("response"), function() {
// Here you will have the second call's results
}
})

This ensures that both the API calls happen in order and only after the first one finishes.这可确保两个 API 调用按顺序发生,并且仅在第一个调用完成后发生。

Note:笔记:

The request library that you are using has been deprecated back in 2020. See https://github.com/request/request Hence, I would suggest you use other libraries like the standard https or http library that is shipped with node or you can use axios . The request library that you are using has been deprecated back in 2020. See https://github.com/request/request Hence , I would suggest you use other libraries like the standard https or http library that is shipped with node or you can使用axios

If you use a forEach loop without awaiting the results, you'll execute them all at the same time.如果您使用 forEach 循环而不等待结果,您将同时执行它们。 Moreover, request library is kind of old and you need to convert its functions to return a promise.此外,请求库有点旧,您需要转换其函数以返回 promise。

Here's how I would do it.这就是我将如何做到的。

const ssn = [1,2,3,4];

function download(item) {
    return new Promise(function(resolve, reject) {
        let options = {}; // construct your request
        request(options, function (error, response) {
            if(error) {
                return reject(error);
            }
            resolve(response);
        })      
    }
}

ssn = ssn.map(async function(item) {
    let res = await download(item);
    // process the result
    return res;
});

You can also use the Bluebird library or get another client library such as got or axios.您还可以使用 Bluebird 库或获取其他客户端库,例如 got 或 axios。

I prefer use async await method for this situation you need install and require async and request-promise after that:对于需要安装的情况,我更喜欢使用 async await 方法,之后需要asyncrequest-promise

const request = require("request-promise");
const async = require("async");
let ssn = [460458524, 637625452, 453311896, 635285187, 455791630, 642348377, 463590491, 450730278, 641201851, 379965491];

async function getCRCDetails() {
  //like a forEache
  async.eachSeries(ssn, async (item) => {
      let CBCOptions = {
        method: "POST",
        url: "https://loanboard.houstondirectauto.com/api/Report",
        headers: {
          "Content-Type": "application/json",
          Cookie: "ci_session=udmojmlc5tfl3epbrmtvgu6nao2f031p",
        },
        body: JSON.stringify({
          token: loantoken,
          action: "CBCReport",
          variables: {
            ssn: item,
          },
        }),
      };
      let EmployerInfoOptions = {
        method: "POST",
        url: "https://loanboard.houstondirectauto.com/api/Report",
        headers: {
          "Content-Type": "application/json",
          Cookie: "ci_session=udmojmlc5tfl3epbrmtvgu6nao2f031p",
        },
        body: JSON.stringify({
          token: loantoken,
          action: "getEmployerInfo",
          variables: {
            ssn: item,
          },
        }),
      };
      try {
        let resultCBCOptions = await request(CBCOptions);
        let EmployerInfoOptions = await request(EmployerInfoOptions);
        console.log(resultCBCOptions)
        console.log(EmployerInfoOptions)
        //do pushing resultCBCOptions
        //do pushing EmployerInfoOptions
      } catch (error) {
        console.log(error);
      }
    },
    () => {
      console.log("finished");
    }
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM