以下为ChatGPT自动生成的解答,正确与否请自行判断。
BFE.devAI解答 - JavaScript 代码题
56. 调取有分页的API
使用常规循环解决:
async function fetchListWithAmount(amount: number = 5) {
let lastItemId: number = undefined;
let result: Array<{ id: number }> = [];
while (result.length < amount) {
const { items } = lastItemId ? await fetchList(lastItemId) : await fetchList();
if (items.length === 0) {
break;
}
lastItemId = items[items.length - 1].id;
result = result.concat(items);
}
return result.slice(0, amount);
}
使用async iterators解决:
async function* itemGenerator() {
let lastItemId: number = undefined;
while (true) {
const { items } = lastItemId ? await fetchList(lastItemId) : await fetchList();
if (items.length === 0) {
break;
}
lastItemId = items[items.length - 1].id;
for (const item of items) {
yield item;
}
}
}
async function fetchListWithAmount(amount: number = 5) {
const result = [];
const iterator = itemGenerator();
for await (const item of iterator) {
if (result.length >= amount) {
break;
}
result.push(item);
}
return result;
}
使用async generators解决:
async function* itemGenerator(lastItemId?: number) {
const { items } = lastItemId ? await fetchList(lastItemId) : await fetchList();
if (items.length === 0) {
return;
}
const newLastItemId = items[items.length - 1].id;
for (const item of items) {
yield item;
}
yield* itemGenerator(newLastItemId);
}
async function fetchListWithAmount(amount: number = 5) {
const iterator = itemGenerator();
const result = [];
for (let i = 0; i < amount; i++) {
const { done, value } = await iterator.next();
if (done) {
break;
}
result.push(value);
}
return result;
}