【问题标题】:How to automate taking X amount of items from array in a loop request如何在循环请求中自动从数组中获取 X 数量的项目
【发布时间】:2021-12-05 08:44:55
【问题描述】:

我有一个充满 id 的大数组(数组大小总是很大,例如超过 1000 个),例如 [000001,000002,000003,000004,...],我想向一个 API 发送一个请求,该 API 最多可以包含 100 个这些 id时间(这是一个限制,每个请求只有 100 个 id,而且我无法控制)

端点将这些 id 作为 url 参数,就像 ?ids=000001,000002,000003,000004,... 一样,但我正在努力找出循环每 100 个条目并获取这些条目所需执行的逻辑,发送请求,然后重复直到所有条目已添加到请求中?

这是我在 SO 上的第一个问题,如果格式不完全正确,我深表歉意,我真的需要对此进行逻辑检查...

【问题讨论】:

    标签: javascript arrays loops request logic


    【解决方案1】:

    一般原则是先将你的大数组分成块,然后从每个块中形成一个请求,发送它,等待响应,保留结果,然后发送下一个。

    这是一些没有细节的代码:

    const chunks = chunkArray(largeArray) // returns an array of arrays
    let responses = []
    for(const chunk of chunks){
        const query = createQueryStringFromArray(chunk)
        const response = await sendQuery(query) // post to API
        responses = [...responses, response] // keep hold of results
    }
    

    【讨论】:

      【解决方案2】:

      你可以像这样使用 JSON:

      let createdJson = JSON.stringify(myIntArray);
      // here send your request with :
      sendRequest("http://url/?json=" + createdJson);
      

      然后,在另一边你使用类似的东西:

      在本例中,我使用的是 PhP。

      $intArray = json_decode($_GET["json"]);
      // now you have your int array
      

      【讨论】:

        猜你喜欢
        • 2017-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多