Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用javaScript调用异步函数直到条件为真?_Javascript_Json_Api - Fatal编程技术网

如何使用javaScript调用异步函数直到条件为真?

如何使用javaScript调用异步函数直到条件为真?,javascript,json,api,Javascript,Json,Api,我有这样一个问题,我正在使用返回假存储数据的API调用,一切正常我正在将接收到的数据推入arr数组,我的目标是调用repeatCall()函数,直到arr.length将arr.length==100,而且问题是,有时我想根据条件过滤接收到的数据,然后将其推入arr数组,在这种情况下,最佳解决方案是什么 让arr=[]; 异步函数repeatCall(){ const req=等待取数(`https://fakestoreapi.com/products`); const resp=wait

我有这样一个问题,我正在使用返回假存储数据的API调用,一切正常我正在将接收到的数据推入
arr
数组,我的目标是调用
repeatCall()
函数,直到
arr.length
arr.length==100
,而且问题是,有时我想根据条件过滤接收到的数据,然后将其推入
arr
数组,在这种情况下,最佳解决方案是什么

让arr=[];
异步函数repeatCall(){
const req=等待取数(`https://fakestoreapi.com/products`);
const resp=wait req.json();
arr.push(…resp)
控制台日志(arr.length)
}

repeatCall()
在arr.length上使用if条件,它将获取api,直到长度等于100

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)
    if(arr.length < 100){
              repeatCall();
    }
}
让arr=[];
异步函数repeatCall(){
const req=等待取数(`https://fakestoreapi.com/products`);
const resp=wait req.json();
arr.push(…resp)
控制台日志(arr.length)
如果(平均长度<100){
repeatCall();
}
}
至于在将数据推送到数组之前过滤数据

let arr = [];
    async function repeatCall() {
        const req = await fetch(`https://fakestoreapi.com/products`);
        const resp = await req.json();
        resp.foreach(item => {
           if(condition){
              arr.push(item);
           }   
           else{
              console.log("don't push")             
           }    
        })
       
        if(arr.length < 100){
                  repeatCall();
        }
        console.log(arr.length)
    }
让arr=[];
异步函数repeatCall(){
const req=等待取数(`https://fakestoreapi.com/products`);
const resp=wait req.json();
每项费用(项目=>{
如果(条件){
arr.push(项目);
}   
否则{
console.log(“不要推”)
}    
})
如果(平均长度<100){
repeatCall();
}
控制台日志(arr.length)
}

while(arr.length@bergi)我使用的是promissions,所以我有这个错误,
await只在异步函数和顶级模块体中有效
但是你把它放在了
async function repeatCall(){
中,而原始代码并没有导致这个错误?别忘了
返回
repeatCall()
result,否则将无法正确处理错误