Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
150
rated 0 times [  155] [ 5]  / answers: 1 / hits: 16144  / 7 Years ago, sun, february 19, 2017, 12:00:00

Is there a better/more beautiful way to call multiple APIs after another (in serial) as in my example?



  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...

}
})

}
})

}
})

More From » node.js

 Answers
15

Depending on which version of node you are using, promises should be 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');

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

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

[#58870] Friday, February 17, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
monica

Total Points: 308
Total Questions: 102
Total Answers: 109

Location: Saudi Arabia
Member since Sat, Aug 20, 2022
2 Years ago
;