【发布时间】:2021-05-03 09:48:19
【问题描述】:
我有这样一个问题,我正在使用返回假存储数据的 API 调用,一切正常我正在将接收到的数据推送到 arr 数组中,我的目标是调用 repeatCall() 函数直到 arr.length 将是 @ 987654324@,另外问题是,有时我想根据条件过滤接收到的数据,然后将其推送到arr数组中,这种情况下的最佳解决方案是什么?
let arr = [];
async function repeatCall() {
const req = await fetch(`https://fakestoreapi.com/products`);
const resp = await req.json();
arr.push(...resp)
console.log(arr.length)
}
repeatCall()
【问题讨论】:
-
while (arr.length <= 100) { const req = await …; …; arr.push(...resp.filter(condition)); } return arr;? -
@bergi 我正在使用承诺,所以我有这个错误,
await is only valid in async functions and the top-level bodies of modules -
但是你把那个放在
async function repeatCall() {里面,原来的代码没有导致那个错误?
标签: javascript json api