[英]how to use while loop in generator function
i'm new to generator function and trying execute while loop inside it.我是生成器 function 的新手,并尝试在其中执行 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;
}
but it return null
even though the while loop have not completed for search.但它返回
null
即使 while 循环尚未完成搜索。
const data = yield call(findRandomData, resp['res'], name);
Error Error: Could not find id at findRandomData
错误
Error: Could not find id at findRandomData
what is it that i'm doing wrong我做错了什么
Try to give a value to viableId variable when you declare it, for example: let viableId = "";在你声明它的时候尝试给viableId变量赋值,例如:letviableId = ""; // if your variable will receive a string value
// 如果你的变量将接收一个字符串值
Or give it a number value (generally people uses 0) if you're working with numbers.如果您使用数字,或者给它一个数字值(通常人们使用 0)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.