JavaScript,React-同时发送多个ajax调用 [英] JavaScript, React - sending multiple simultaneous ajax calls

查看:328
本文介绍了JavaScript,React-同时发送多个ajax调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的React应用程序中,我有一个参数数组(例如,一些ID),应将其用作ajax调用队列的参数.问题在于数组可能包含1000多个项目,如果我仅使用forEach循环递归地进行ajax调用,浏览器页面最终将在每个请求得到解决之前停止响应.

In my React application I have an array of parameters (some IDs, for example), which should be used as a parameters for an ajax call queue. The problem is that array might contain more than 1000 items and if I just recursively make the ajax call using the forEach loop, the browser page eventually stops responding before each of the requests are resolved.

是否有一种技术/库,可以允许异步发送ajax请求,例如一次发送5个请求,并且仅在完成这些请求后才继续发送下一个5个请求?

Is there a technique/library, which could allow to send ajax requests, for example, by 5 requests at a time asynchronously, and only when those are finished, proceed the next 5?

后续问题:

反应-控制多个Ajax调用

反应-控制对服务器的AJAX调用

推荐答案

如果您不受es版本的限制,可以使用es6,则应考虑异步等待

if you are not constrained by es version and can use es6 then you should look into async await

async function makeBatchCalls(arrayIds, length) {
    let test = arrayIds.reduce(
        (rows, key, index) => (index % length == 0 
            ? rows.push([key]) 
            : rows[rows.length - 1].push(key)
        ) && rows, 
        []
    );

    let Batchresults = [];

    //convert them to two dimensionl arrays of given length [[1,2,3,4,5], [6,7,8,9,10]]
    for (calls of test) {
       Batchresults.push(
           await Promise.all(
               calls.map((call) => fetch(`https://jsonplaceholder.typicode.com/posts/${call}`))
           )
       );
    }

    return Promise.all(Batchresults); //wait for all batch calls to finish
}

makeBatchCalls([1,2,3,4,5,6,7,8,9,10,12,12,13,14,15,16,17,18,19,20],3)

async/await用于等待异步调用的确切情况.基本上在异步函数内部,直到解决了等待问题,然后暂停执行.在开始使用承诺和生成器之前,您需要了解它们.

async/await is meant for the exact scenario of awaiting async calls. basically inside the async function until await is resolved the execution is suspended. You would need to understand promises and generators before you start using them.

这篇关于JavaScript,React-同时发送多个ajax调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆