简体   繁体   中英

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?

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);
    });
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM