2 回答

TA貢獻1886條經(jīng)驗 獲得超2個贊
只有當循環(huán)位于當前函數(shù)內時,您才能從循環(huán)中中斷。如果循環(huán)在函數(shù)之外(例如,.then回調),您就無法擺脫它。
而不是使用.then,將awaited 字符串分配給一個變量并檢查它(并確保檢查字符串,而'THE END'不是results數(shù)組):
async something() {
const results = [];
for (let i = 0;i < 999;i++) {;
const string = await rp('/api?id=1page='+i);
results.push(string);
if(string === 'THE END') {
break;
}
}
// do something with results
}
請注意,由于您將解析的值本身推送到results數(shù)組,因此無需調用Promise.all數(shù)組。

TA貢獻1805條經(jīng)驗 獲得超9個贊
考慮到這rp是請求您的網(wǎng)址的功能,這是我能想到的最簡單的答案。
let results = []
for (let i = 0;i < 999;i++) {//if i is greater than or equal 999, the loop will end
await rp('/api?id=1page='+i).then(string => {
results.push(string)
if(results === 'THE END') {
//do stuffs you need to do
// break here
i = 1000;
}
})
}
添加回答
舉報