打破请求-承诺的循环

/api?id=1&page=每次请求不同的页面时,我都会 遍历这个 url ,直到得到我想要的结果。


我不知道如何以及为什么不能从请求中停止循环。


async something() {


  let results = []

  for (let i = 0;i < 999;i++) {

    await rp('/api?id=1page='+i).then(string => {

     results.push(string)

     if(results === 'THE END') {

        // break here

     }

    })

  }

  Promise.all(results).then(res => {

   // do something

  })

}


守候你守候我
浏览 115回答 2
2回答

MM们

只有当循环位于当前函数内时,您才能从循环中中断。如果循环在函数之外(例如,.then回调),您就无法摆脱它。而不是使用.then,将awaited 字符串分配给一个变量并检查它(并确保检查字符串,而'THE END'不是results数组):async something() {&nbsp; const results = [];&nbsp; for (let i = 0;i < 999;i++) {;&nbsp; &nbsp; const string = await rp('/api?id=1page='+i);&nbsp; &nbsp; results.push(string);&nbsp; &nbsp; if(string === 'THE END') {&nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }&nbsp; }&nbsp; // do something with results}请注意,由于您将解析的值本身推送到results数组,因此无需调用Promise.all数组。

Cats萌萌

考虑到这rp是请求您的网址的功能,这是我能想到的最简单的答案。let results = []&nbsp; for (let i = 0;i < 999;i++) {//if i is greater than or equal 999, the loop will end&nbsp; &nbsp; await rp('/api?id=1page='+i).then(string => {&nbsp; &nbsp; &nbsp;results.push(string)&nbsp; &nbsp; &nbsp;if(results === 'THE END') {&nbsp; &nbsp; &nbsp; &nbsp; //do stuffs you need to do&nbsp; &nbsp; &nbsp; &nbsp; // break here&nbsp; &nbsp; &nbsp; &nbsp; i = 1000;&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; })&nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript