【问题标题】:How to call async Function until condition is true using javaScript?如何使用javascript调用异步函数直到条件为真?
【发布时间】: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


【解决方案1】:

在 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();
    }
}

至于在将数据推送到数组之前对其进行过滤。

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)
    }

【讨论】:

  • 不要忘记return repeatCall() 结果,否则将无法正确处理错误
猜你喜欢
  • 2021-06-24
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
  • 2022-12-04
  • 1970-01-01
  • 2012-02-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多