【问题标题】:While loop on Node.js with asynchronous data使用异步数据在 Node.js 上循环
【发布时间】:2018-09-04 02:25:02
【问题描述】:

我正在使用 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() 也应该有一种方式来反馈错误。

标签: javascript node.js asynchronous while-loop


【解决方案1】:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2017-06-16
  • 2015-04-11
  • 1970-01-01
  • 2017-05-16
  • 1970-01-01
  • 2013-02-16
  • 2015-02-27
  • 1970-01-01
相关资源
最近更新 更多