Nodejs在一个函数中循环http请求

我已经能够使用bluebird在一个函数中并行运行一个http get请求数组,这个函数完成之后会返回每个请求的响应。 不过,我希望按顺序链接请求,而不会影响下面显示的当前函数中承诺的asynchronous行为。

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

Interesting Posts