简体   繁体   English

NodeJ,承诺不等待

[英]NodeJs, Promises not waiting

I have this function that should make 300 requests for a web page (for benchmarking), however the Promise.all is not waiting for those requests to finish before outputting an empty array, any ideas? 我有这个功能,应该对一个网页发出300个请求(用于基准测试),但是Promise.all在输出空数组之前没有等待这些请求完成,有什么想法吗?

function requestLoop(){

  var resultSet= [];

  // options.requests = 300
  // options.url = http://localhost/

  for(var c=1;c<=options.requests; c++){

    http.get(options.url, function(res){

    //  resultSet.push( { request: c, statusCode: res.statusCode});

      resultSet.push(new Promise(function(res){ return { request: c, statusCode: res.statusCode}; }));

    });

  }

  Promise.all(resultSet).then(function(){
    console.log(resultSet);
  });

  return;

}

Promise is bluebird and http is the normal http package Promise是bluebird,而http是正常的http包

Promise is being pushed in array in callback. Promise正在回调中推入数组。 Hence By the time Promise.all invokes, array is empty( [] ) 因此,到Promise.all调用时,array为空( []

Push new Promise in array within loop itself, not in callback 在循环本身而不是callback中将new Promisenew Promise数组中

function requestLoop() {
  var resultSet = [];
  for (var c = 1; c <= options.requests; c++) {
    (function(c) {
      resultSet.push(new Promise(function(resolve) {
        http.get(options.url, function(res) {
          resolve({
            request: c,
            statusCode: res.statusCode
          });
        });
      }));
    })(c);
  }
  Promise.all(resultSet).then(function() {
    console.log(resultSet);
  });
}

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

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