循环包含回调的函数

时间:2016-08-05 14:58:35

标签: javascript node.js callback

我正在尝试使用NodeJS 6.3.1重复类似的异步函数来访问分页数据。目的是根据总行数和每页行数计算数据页数,然后使用请求包调用API以检索每页数据。

例如,如果共有34行,每页有10条记录,我需要调用以下每个URL。

www.example.com?page=1
www.example.com?page=2
www.example.com?page=3
www.example.com?page=4

鉴于每个调用都需要回调,我如何迭代它们?

1 个答案:

答案 0 :(得分:1)

以下是使用Promise.all()的方法:

// This is will be your get request function
function getRequest(url) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve(url);
    }, 2000);
  });
}

var promises = [];
var url = 'www.example.com?page=';

for (var i = 1; i < 10; i++) {
  // Creating a list of promises (get requests)
  promises.push(getRequest(url + i));
}

// After all of the promises have resolved, all of the responses will be
// concatinated into a list of responses and passed in like this:
Promise.all(promises).then(function(allResponses) {
  console.log(allResponses);
});

更新

如果您使用的是默认节点请求,getRequest()方法将如下所示:

var request = require('request');

function getRequest(url) {
  return new Promise(function(resolve, reject) {
    request(url, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        resolve(body); // or resolve(response) if that is what you are looking for
      } 
      reject(error);
    });
  });
}