Reputation: 75
I'm using the Request module to make a GET request on Node.js. However the while loop is never broken.
//this function calls the paging function until page.paging.next is undefined
function createLikes(page){
addLikes(page)
while (typeof page.paging.next !== "undefined") {
paging(page,function(resp){
page = resp
console.log(page)
})
}
}
function paging(page, callback){
request.get({url: page.paging.next},
(error, response, body) => {
if(error) {
return console.dir(error);
}
return callback(JSON.parse(body))
})
}
How can i fix this considering that console.log inside the callback function logs the expected data?
I used the solution given below by CertainPerformance and it worked out up to the point that it needed to exit the loop, then it gave me a unhandled promise rejection error. What's wrong?
Upvotes: 2
Views: 3139
Reputation: 370789
paging
runs asynchronously, but your while loop runs synchronously. Try using await
instead, so that the while
loop waits for the asynchronous resolution with each iteration:
async function createLikes(page) {
addLikes(page)
while (typeof page.paging.next !== "undefined") {
page = await new Promise((resolve, reject) => {
paging(page, resolve);
});
}
}
Upvotes: 4