Guilherme Marques
Guilherme Marques

Reputation: 75

While loop on Node.js with asynchronous data

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?

Edit:

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

Answers (1)

CertainPerformance
CertainPerformance

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

Related Questions