如何在生成器函数中使用 while 循环



我是生成器函数的新手,并尝试在其中循环时执行。

export function* findRandomData(list, name) {
let searchList = true;
const formattedName = name
.replace(new RegExp('_', 'g'), ' ')
.toLowerCase();
const indexesToSearch = [];
for (let i = 0; i < list.length; i++) {
indexesToSearch.push(i);
}
let viableId;
// Search through results
while (searchList) {
// If there are no results left then finish
if (indexesToSearch.length === 0) {
searchList = false;
throw new Error('Could not find id');
}
// Find a random number that has not been selected already, then remove
const randomPosition = Math.floor(Math.random() * indexesToSearch.length);
indexesToSearch.splice(randomPosition, 1);
let title = list[randomPosition].title;
viableId = list[randomPosition].id;
const eligible = yield call(
isEligibleVideo,
title,
formattedName,
viableId
);
if (eligible) {
searchList = false;
}
}
return viableId;
}

但它返回null即使 while 循环尚未完成搜索。

const data = yield call(findRandomData, resp['res'], name);

错误Error: Could not find id at findRandomData

我做错了什么

当你声明它时,尝试给 viableId 变量一个值,例如: 让 可行ID = ";如果您的变量将收到字符串值

或者,如果您正在使用数字,请给它一个数字值(通常人们使用 0(。

最新更新