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

查看:26
本文介绍了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?

后续问题:

React - 控制多个 Ajax 调用

React - 控制对服务器的 AJAX 调用

推荐答案

如果你不受 es 版本的限制并且可以使用 es6 那么你应该看看 async await

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 执行被挂起.在开始使用它们之前,您需要了解 Promise 和生成器.

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天全站免登陆