首页 > 解决方案 > 需要使用node js在循环中调用两个API

问题描述

我有一个 ssn 号码数组,我有两个 api 列表,我需要在其中将 ssn 号码作为请求 json 传递,所以我需要在 ssn 循环内调用两个 api,所以我在调用两个 api 期间将 ssn 传递给 json 请求,但代码不起作用正确地同时调用两个api,我需要一个一个调用两个api。

API详细信息和代码如下

我的代码:

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);

      })

}

这里我需要一一调用API请求。请大家指导我。

标签: javascriptnode.js

解决方案


在 Node 中,您使用的请求方法是异步的。这意味着运行代码的运行程序(服务器)不会等待请求完成,而是继续执行下一行。

你可以做的一件事是,

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
}
})

这可确保两个 API 调用都按顺序发生,并且仅在第一个调用完成后发生。

笔记:

您使用的request库已于 2020 年弃用。请参阅https://github.com/request/request因此,我建议您使用其他库,例如node 附带的标准https或库,或者您可以使用.httpaxios


推荐阅读