Answer the question
In order to leave comments, you need to log in
Node.js what do I need, synchronous or asynchronous?
Hello, I need to make an unknown number of requests to the server until there is no json key in the response.
request({url:url}, function(err, response, body){
let data = JSON.parse(body);
while(data.nextPageToken !== undefined){
var newUrl = url + '&pageToken=' + data.nextPageToken;
request({url: newUrl}, function(err, response, body){
newUrl = url + '&pageToken=' + JSON.parse(body).nextPageToken;
})
}
})
Answer the question
In order to leave comments, you need to log in
node v7.6+ or transpiling babel async2generators
function requestAsync(params) {
return new Promise((resolve, reject) => {
request(params, (err, response, body) => {
if(err) { return reject(err); }
resolve({response, body});
});
});
}
async function getURL(_url) {
var data, url = _url;
do {
const {body} = await requestAsync({url});
data = JSON.parse(body);
url = _url + '&pageToken=' + data.nextPageToken;
} while(data.nextPageToken !== undefined);
return data;
}
There is a solution like this
var page = 2,
lastPage = 100;
async.whilst(function () {
return page <= lastPage;
},
function (next) {
request("http://some_json_server.com/data?page=" + page, function (error, response, body) {
if (!error && response.statusCode == 200) {
store_data(body)
}
page++;
next();
});
},
function (err) {
// All things are done!
});
await request({}, function(){})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question