我想在遍历数组以调用API函数时使用生成器函数。
我尝试使用setTimeout,但是功能没有暂停。它进行了2500次调用,并导致CORS提取API错误。
function* subjectGenerator(){
subjects.forEach(subject=>{
let examyear = startYear;
while (examyear <= endYear) {
const api = createQuestionsURLApi(subject, examyear);
// this.subject = subject.toLowerCase();
getQuestionFromURL(api, subject);
console.log(subject, api);
yield examyear++;
}
});
}
我希望收益能够被接受,所以我可以使用subjectGenerator.next()进行循环。
答案 0 :(得分:1)
感谢@briosheje
function* subjectGenerator(){
for(let i = 0; i < subjects.length; i++){
const subject = subjects[i];
let examyear = startYear;
while (examyear <= endYear) {
const api = createQuestionsURLApi(subject, examyear);
getQuestionFromURL(api, subject);
console.log(subject, api);
yield examyear++;
}
}
}