如何使用Nodejs中的Promise进行同步http调用

我想使用Q Promises同步进行http呼叫,我有100名学生,我需要每个人从另一个平台获取一些数据,并且这样做是通过Q Promises尝试的,但它似乎并不像是在同步。

如何确保一旦完成parsing响应并插入到mongodb中后,又不会进行另一个调用:

我的代码到目前为止是这样的:

var startDate = new Date("February 20, 2016 00:00:00"); //Start from February var from = new Date(startDate).getTime() / 1000; startDate.setDate(startDate.getDate() + 30); var to = new Date(startDate).getTime() / 1000; iterateThruAllStudents(from, to); function iterateThruAllStudents(from, to) { Student.find({status: 'student'}) .populate('user') .exec(function (err, students) { if (err) { throw err; } async.eachSeries(students, function iteratee(student, callback) { if (student.worksnap.user != null) { var worksnapOptions = { hostname: 'worksnaps.com', path: '/api/projects/' + project_id + '/time_entries.xml?user_ids=' + student.worksnap.user.user_id + '&from_timestamp=' + from + '&to_timestamp=' + to, headers: { 'Authorization': 'Basic xxxx=' }, method: 'GET' }; promisedRequest(worksnapOptions) .then(function (response) { //callback invoked on deferred.resolve parser.parseString(response, function (err, results) { var json_string = JSON.stringify(results.time_entries); var timeEntries = JSON.parse(json_string); _.forEach(timeEntries, function (timeEntry) { _.forEach(timeEntry, function (item) { saveTimeEntry(item); }); }); }); callback(); }, function (newsError) { //callback invoked on deferred.reject console.log(newsError); }); } }); function saveTimeEntry(item) { Student.findOne({ 'worksnap.user.user_id': item.user_id[0] }) .populate('user') .exec(function (err, student) { if (err) { throw err; } student.timeEntries.push(item); student.save(function (err) { if (err) { console.log(err); } else { console.log('item inserted...'); } }); }); } function promisedRequest(requestOptions) { //create a deferred object from Q process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; var deferred = Q.defer(); var req = http.request(requestOptions, function (response) { //set the response encoding to parse json string response.setEncoding('utf8'); var responseData = ''; //append data to responseData variable on the 'data' event emission response.on('data', function (data) { responseData += data; }); //listen to the 'end' event response.on('end', function () { //resolve the deferred object with the response console.log('http call finished'); deferred.resolve(responseData); }); }); //listen to the 'error' event req.on('error', function (err) { //if an error occurs reject the deferred deferred.reject(err); }); req.end(); //we are returning a promise object //if we returned the deferred object //deferred object reject and resolve could potentially be modified //violating the expected behavior of this function return deferred.promise; } 

任何人都可以告诉我该怎么做才能做到这一点? 这也是可能的,所以我知道什么时候所有的http调用完成,插入完成了所有…

我会放弃你目前的做法,并使用npn结节请求承诺。 https://www.npmjs.com/package/request-promise

这是非常stream行和成熟。

 rp('http://your/url1').then(function (response1) { // response1 access here return rp('http://your/url2') }).then(function (response2) { // response2 access here return rp('http://your/url3') }).then(function (response3) { // response3 access here }).catch(function (err) { }); 

现在你只需要将它转换为你想要的100个请求的迭代,并完成工作。