NodeJS:串行编写多个API调用的好方法
有没有更好/更美丽的方式来调用多个API接连(串行)如我的例子?
var request = require('request'); request('http://www.test.com/api1', function (error, response, body) { if (!error && response.statusCode == 200) { request('http://www.test.com/api1', function (error, response, body) { if (!error && response.statusCode == 200) { request('http://www.test.com/api1', function (error, response, body) { if (!error && response.statusCode == 200) { //And so on... } }) } }) } })
根据您使用的节点版本,promise应该是native …
https://nodejs.org/en/blog/release/v4.0.0/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
var request = require('request'); function getRequest(url) { return new Promise(function (success, failure) { request(url, function (error, response, body) { if (!error && response.statusCode == 200) { success(body); } else { failure(error); } }); }); } getRequest('http://www.test.com/api1').then(function (body1) { // do something with body1 return getRequest('http://www.test.com/api2'); }).then(function (body2) { // do something with body2 return getRequest('http://www.test.com/api3'); }).then(function (body3) { // do something with body3 //And so on... });
使用async.series
如果你想对一组URL做同样的操作,可以使用async.map
无极也可以用别人的build议。
如果你是asynchronous编程的新手,我build议先从async
模块开始,然后转向Promise
(或者coroutines
, async/await
),一旦你有了更清晰的理解。
例:
var request = require('request'); async.series([ function(callback) { request('http://www.test.com/api1', function(error, response, body) { if (!error && response.statusCode == 200) { return callback(null, response); } return callback(error || new Error('Response non-200')); } }, function(callback) { request('http://www.test.com/api2', function(error, response, body) { if (!error && response.statusCode == 200) { return callback(null, response); } return callback(error || new Error('Response non-200')); } } ], // optional callback function(err, results) { if (err) { // Handle or return error } // results is now array of responses });
你可以使用request-promise
而不是request
,然后你可以链接所有的承诺!
https://github.com/request/request-promise
var rp = require('request-promise'); rp(options) .then(function (body) { return rp(...) }).then(()){ ... }
在我诚实的意见,如果命令不重要,你应该并行地做所有的要求!
你可能要考虑使用JavaScript的承诺 。 他们确实提供了一个more beautiful
方式来处理callback。