我的问题是:鉴于提供的(非常简单的)生成器,是否可以将生成器恢复到其原始状态以便再次使用?
var generator = function*() {
yield 1;
yield 2;
yield 3;
};
var iterable = generator();
for (let x of iterable) {
console.log(x);
}
// At this point, iterable is consumed.
// Is there a method for moving iterable back
// to the start point by only without re-calling generator(),
// (or possibly by re-calling generator(), only by using prototype
// or constructor methods available within the iterable object)
// so the following code would work again?
for (let …Run Code Online (Sandbox Code Playgroud) 我编写了这段代码来迭代具有特定数字(如分页)的 github 问题,在本例中一次有 3 个问题:
const getUrl = (page) => `https://api.github.com/repos/angular/angular/issues?page=${page}`;
const getIssues = async function*() {
for (let p = 1; true; p++) {
const url = getUrl(p);
const rawData = await fetch(url, {
headers: { 'User-Agent': 'app' }
});
const issues = await rawData.json();
for (let issue of issues) {
yield issue;
}
}
};
const generator = getIssues();
document.querySelector('[data-next]').addEventListener('click', async function() {
let i = 0;
for await (let issue of generator) {
console.log(issue);
if (++i === …Run Code Online (Sandbox Code Playgroud)