【问题标题】:nodejs request function inside for loopfor循环内的nodejs请求函数
【发布时间】:2020-11-02 04:58:10
【问题描述】:

我有这个数组,每个数组有 8 个项目

var array_pullrequest_id=["335","328","326","323","322","314","295","291"];
var array_uniqueName=["A@A.com","B@B.com","C@C.com","D@D.com","E@E.com","F@F.com","G@G.com","H@H.com"];

我正在尝试对数组的每个索引进行发布请求:

 function test2(){
   
    var array_pullrequest_id=["335","328","326","323","322","314","295","291"];
    var array_uniqueName=["A@A.com","B@B.com","C@C.com","D@D.com","E@E.com","F@F.com","G@G.com","H@H.com"];
    var count = 8;
     for (var i=0; i<count; i++){
     
    var pullRequests_id = array_pullrequest_id[i];    
    var createdBy = array_uniqueName[i];
  
  console.log("first index: " + i);
  console.log("first console log pullRequest ID: " + pullRequests_id);
  console.log("first console log Created by: " + createdBy);

  var options = {
  'method': 'GET',
  'url': 'https://HIDEN_URL/pullRequests/'+ pullRequests_id+'/workitems',
  'headers': {
    'Authorization': 'Basic HIDEN_AUTH',
    'Cookie': 'HIDEN_COOKIE'
  }
}
request(options, function (error, response) { 
    console.log("second index: " + i);
    console.log("second console log pullRequest ID: " + pullRequests_id);
    console.log("second console log Created by: " + createdBy);

});
}
 }

现在这是控制台输出:

first index: 0
first console log pullRequest: 335
first console log Created by: A@A.com
first index: 1
first console log pullRequest: 328
first console log Created by: B@B.com
first index: 2
first console log pullRequest: 326
first console log Created by: C@C.com
first index: 3
first console log pullRequest ID: 323
first console log Created by: D@D.com
first index: 4
first console log pullRequest ID: 322
first console log Created by: E@E.com
first index: 5
first console log pullRequest ID: 314
first console log Created by: F@F.com
first index: 6
first console log pullRequest ID: 295
first console log Created by: G@G.com
first index: 7
first console log pullRequest ID: 291
first console log Created by: H@H.com
second index: 8
second console log pullRequest ID: 291
second console log Created by: H@H.com
second index: 8
second console log pullRequest ID: 291
second console log Created by: H@H.com
second index: 8
second console log pullRequest ID: 291
second console log Created by: H@H.com
second index: 8
second console log pullRequest ID: 291
second console log Created by: H@H.com
second index: 8
second console log pullRequest ID: 291
second console log Created by: H@H.com
second index: 8
second console log pullRequest ID: 291
second console log Created by: H@H.com
second index: 8
second console log pullRequest ID: 291
second console log Created by: H@H.com
second index: 8
second console log pullRequest ID: 291
second console log Created by: H@H.com

现在您可以看到 第一个控制台日志 项目在计数变量索引之后正确打印,但在 for 循环请求函数 (第二个控制台日志) 内它是唯一的打印最后一个数组项,即使它在循环内,它也只是最后一个,这对我来说没有意义......

【问题讨论】:

  • request 我相信是一个异步函数,所以第一个控制台日志和第二个控制台日志没有按顺序执行。循环首先完成,然后请求函数将获取循环结束时设置的最后一个变量值,这就是为什么第二个控制台日志打印 291 和 H2H.com
  • @grandia 你推荐我在nodejs中做非异步http请求的其他方法吗?
  • 我建议使用其他框架,因为 request 似乎已被弃用。我用过 axios 和 fetch,我觉得两者都很棒。为了使其同步,您可以使用 async/await。你熟悉 async/await 吗?
  • 感谢您的建议,我不熟悉 async/await,但我会尝试更改为这些框架 :)!
  • 当然,让我贴一个代码

标签: javascript node.js api https request


【解决方案1】:

假设你已经安装了 axios,你可以像下面这样使用 async/await

注意function test2()前面的async关键字

现在test2 是一个异步函数

const axios = require('axios');

async function test2(){
   
    var array_pullrequest_id=["335","328","326","323","322","314","295","291"];
    var array_uniqueName=["A@A.com","B@B.com","C@C.com","D@D.com","E@E.com","F@F.com","G@G.com","H@H.com"];
    var count = 8;
    for (var i=0; i<count; i++){

        var pullRequests_id = array_pullrequest_id[i];    
        var createdBy = array_uniqueName[i];

        console.log("first index: " + i);
        console.log("first console log pullRequest ID: " + pullRequests_id);
        console.log("first console log Created by: " + createdBy);

        var options = {
        'method': 'GET',
        'url': 'https://HIDEN_URL/pullRequests/'+ pullRequests_id+'/workitems',
        'headers': {
        'Authorization': 'Basic HIDEN_AUTH',
        'Cookie': 'HIDEN_COOKIE'
            }
        }
        await axios(options)
        .then(() => {
            console.log("second index: " + i);
            console.log("second console log pullRequest ID: " + pullRequests_id);
            console.log("second console log Created by: " + createdBy);
        })
        
    }
 }

【讨论】:

    【解决方案2】:

    您也可以使用 async for 循环“如果您的节点版本支持它”,如上所述,您的代码的问题是请求本质上是异步的。

    【讨论】:

      【解决方案3】:

      发出服务请求本质上是阻塞的,因此我们应该使用回调或承诺来获得您期望的输出。尝试使用 asyncForEach 可以实现上述输出。

      async function test2() {
      
          var array_pullrequest_id = ["335", "328", "326", "323", "322", "314", "295", "291"];
          var array_uniqueName = ["A@A.com", "B@B.com", "C@C.com", "D@D.com", "E@E.com", "F@F.com", "G@G.com", "H@H.com"];
          var count = 8;
      
          await asyncForEach(array_pullrequest_id, async(pullrequest, index) => {
              var pullRequests_id = array_pullrequest_id[index];
              var createdBy = array_uniqueName[index];
      
              console.log("first index: " + index);
              console.log("first console log pullRequest ID: " + pullRequests_id);
              console.log("first console log Created by: " + createdBy);
      
              var options = {
                  'method': 'GET',
                  'url': 'https://HIDEN_URL/pullRequests/' + pullRequests_id + '/workitems',
                  'headers': {
                      'Authorization': 'Basic HIDEN_AUTH',
                      'Cookie': 'HIDEN_COOKIE'
                  }
              }
              request(options, function(error, response) {
                  console.log(error);
                  console.log("second index: " + index);
                  console.log("second console log pullRequest ID: " + pullRequests_id);
                  console.log("second console log Created by: " + createdBy);
      
              });
          });
      }
      
      async function asyncForEach(array, callback) {
          for (let index = 0; index < array.length; index++) {
              await callback(array[index], index, array);
          }
      }
      

      【讨论】:

        【解决方案4】:

        第二个控制台日志之所以只打印数组中的最后一项,是因为它在 request 内部,这是一个 asynchronous 函数,这意味着当 request 函数在后台返回一个承诺请求函数之外的其余代码正常运行,因此循环不断迭代直到数组中的最后一项

        【讨论】:

          猜你喜欢
          • 2021-05-28
          • 1970-01-01
          • 1970-01-01
          • 2016-09-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-10-05
          相关资源
          最近更新 更多