I need to make HTTP requests (currently using request for that, but can use an alternate way if possible) to a service that includes some kind of pagination. The problem is, I don't know how to get to page n+1 until I receive page n. This is why the calls need to happen after each other, after the call before it is finished.
I imagine that I probably need to make sync calls to make this happen, or maybe have a trigger at the end of each callback to start the next http call, but I am unsure how to do either.
Short example here:
var request = require('request');
var the_headers = {...}
request({
method: "GET",
url: "the_url",
headers: the_headers,
qs: {
limit:5
}
}, function(error, response, body){
if(error){
console.log(error);
}else{
console.log(JSON.parse(body)); //<--data for the next call would be here
}
});
Thank you!
Edit:
Code snippet using promises (q library):
var q = require('q');
var request = require('request');
var the_headers = {...}
function findTopPosts(){
var qPromise = q.defer();
request({
method: "GET",
url: "the_url",
headers: the_headers, //the_headers is a global variable
qs: {
limit:5
}
}, function(error, response, body){
if(error){
qPromise.reject(error);
}else{
var after = body.data.after; // <-- information that I need
qPromise.resolve(JSON.parse(body))
}
});
return qPromise.promise;
}