Nodejs在函数中循环http请求

时间:2016-08-12 19:46:30

标签: node.js http express promise bluebird

我已经能够使用bluebird在一个函数中并行运行一个http get请求数组,该函数在完成所有请求后返回每个请求的响应。但是,我想按顺序链接请求以一个接一个地运行,而不会影响下面显示的当前函数中promises的异步行为。

var Promise = require('bluebird');

function buildCartWithItems(cartID,requests, cookie) {

  var promises = [];

  for (idx in requests) {

    var request = requests[idx]; // requests is an array containing the json records of each request parameter 
    request["id"] = cartID;

    promises.push(new Promise(function(resolve, reject) {

        var options = {
          host: 'example.com',
          path: "/example/addToCart?"+param(request),
          headers: {'Cookie': cookie, 'Connection': 'keep-alive'}
        };

        https.get(options, function (response) {
          var body = '';

          response.on('data', function(d) {
            body += d;
          });

          response.on('end', function() {
            console.log("jsonservicesPostRequest response: " + body);
            var parsed = JSON.parse(body);
            if (parsed["STATUS"] == "success") {
              resolve(parsed.RESULT.itemGroup.id);
            } else 
              resolve("error");
          });

          response.on('error', function(exception) {
            console.log("auth error: " + exception);
            resolve(exception);
          });
        });
    }));
  }

  return Promise.all(promises);
}

使用:

var cart = 12345; // cart ID
var itemsParams = [];
for (idx in products) {
  var parms = {
    'guid' : prod["_id"]["GUID"],
    'count': prod["deficit"],
  };
  itemsParams.push(parms); 
}

buildCartWithItems(cart,itemsParams,newcookie).then(function(results) {
      // results -> array of all of the cart.id's
      console.log("Build Cart Results: " + JSON.stringify(results));
});

0 个答案:

没有答案