簡體   English   中英

使用異步數據在Node.js上進行While循環

[英]While loop on Node.js with asynchronous data

我正在使用Request模塊在Node.js上進行GET請求。 但是while循環永遠不會中斷。

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

考慮到回調函數中的console.log記錄了預期的數據,我該如何解決?

編輯:

我使用了下面由certainPerformance給出的解決方案,它解決了需要退出循環的問題,然后給了我一個未處理的承諾拒絕錯誤。 怎么了?

paging異步運行,但是while循環同步運行。 嘗試使用await代替,這樣while循環每次迭代都會等待異步解析:

async function createLikes(page) {
  addLikes(page)
  while (typeof page.paging.next !== "undefined") {
    page = await new Promise((resolve, reject) => {
      paging(page, resolve);
    });
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM