简体   繁体   English

承诺循环

[英]For loop with promises

I'm running a for loop which calls a function that does a GET request 我正在运行一个for循环,该循环调用执行GET请求的函数

for (var i = 0; i < uids.length; i++) {

makeRequest(uids[i]);

}

function makeRequest(hostname) {

  request({
    url: url,
    json: true
    }, function(error, response, body) {
    if (!error && response.statusCode === 200) {
    //display the data etc
    }
    }

}

Is it possible for the for loop to ONLY iterate after each request is made and completed. for循环是否有可能仅在提出和完成每个请求之后才进行迭代。 eg once the GET request is complete and returns a result? 例如,一旦GET请求完成并返回结果?

I thought about implementing some timeouts, however I am not sure that that is the best solution for this. 我考虑过要实现一些超时,但是我不确定这是否是最好的解决方案。

Make it recursive until you have items left: 使它递归,直到剩下项目为止:

var itemsLeft = uids.length;

function makeRequest(hostname) {
   request({
      url: url,
      json: true
   }, function(error, response, body) {
     if (!error && response.statusCode === 200) {
        if( itemsLeft !== 0 ) { 
           makeRequest( hostname );
           itemsLeft -= 1;
        } 
     }
   })
}

Can suggest to take a look into something like https://github.com/FuturesJS/forEachAsync . 可以建议看一下https://github.com/FuturesJS/forEachAsync之类的东西。 Check their example to understand how to use the library. 检查他们的示例以了解如何使用该库。

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

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