NodeJs,承诺不等待

时间:2017-04-21 10:45:58

标签: javascript node.js promise

我有这个函数应该对网页提出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是bluebird,http是普通的http包

1 个答案:

答案 0 :(得分:4)

Promise在回调中被推入数组。因此,在Promise.all调用时,数组为空([]

在循环内推送数组new Promise,而不是callback

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