gpt4 book ai didi

javascript - 在 react-redux 应用程序中处理大量 http 请求

转载 作者:行者123 更新时间:2023-11-30 06:50:02 26 4
gpt4 key购买 nike

我的 react-redux 应用程序项目需要一些帮助。我有一些大数据,我将它们分成小文件,用户可以选择开始和结束时间范围。当用户按下“获取数据”按钮时,我创建 http 请求 promise 对象并将其插入数组,然后使用 Promise.all() 等待所有请求完成。它适用于小时间范围,但如果用户选择大时间范围,那么我可以看到应用程序滞后。我在 chrome 开发者工具中看到了 50 多个 HTTP 请求。我想知道在 react-redux 应用程序中处理大量请求的最佳方法是什么?

最佳答案

背景信息:浏览器限制并发请求。例如,Chrome 限制每个主机名 6 个连接,最多 10 个连接。

// Redux actions:
import axios from 'axios';

const LIMIT = 6;

const populateQueue = (requestConfigs) => ({ type: 'POPULATE_QUEUE', payload: requestConfigs });
const popRequest = () => ({ type: 'POP_REQUEST' });

export const initializeQueue = (requestConfigs) => (dispatch) => {
// Grab as many request as we allow to run concurrently
const initialRequests = requestConfigs.slice(0, LIMIT);

// Put the rest in a queue
const remainingRequests = requestConfigs.slice(LIMIT, requestConfigs.length);
dispatch(populateQueue(remainingRequests));

// Start the first batch. When one of requests finishes,
// it will pop the next from the queue and start it.
initialRequests.forEach((requestConfig) => dispatch(startRequest(requestConfig)));
};

const startRequest = (requestConfig) => async (dispatch, getState) => {
try {
await axios(requestConfig);
// process response here
} catch(error) {
// error handling
} finally {
const { queue } = getState().queuedRequests;
if (queue.length) {
// Queue not empty yet, start the next request
const next = queue[0];
dispatch(popRequest());
dispatch(startRequest(next));
}
}
};

// Reducer:
const initialState = {
queue: []
};

const queuedRequestReducer = (state = initialState, action) => {
if (action.type === 'POPULATE_QUEUE') {
return { queue: action.payload };
} else if (action.type === 'POP_REQUEST') {
return { queue: state.queue.slice(1, state.queue.length) };
}

return state;
};

export default queuedRequestReducer;

// In the React component this would be triggered with:
<button onClick={() => initializeQueue(requestConfigs)}>fetch a lot of data</button>

关于javascript - 在 react-redux 应用程序中处理大量 http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58775992/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com