2

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?

1
  • Something tells me that paging() should also have a way of communicating back an error. Commented Mar 26, 2018 at 3:06

1 Answer 1

4

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);
    });
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

There's also request-promise to avoid the callback shenanigans.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.