我正在处理这样一种情况:每当我进行多个 api 调用时,它不应该同时调用所有 api,而是应该在 api 调用正在进行时将其推送到队列,一旦我得到响应,我就必须创建一个 api如果队列长度大于0,则从队列中调用。
let queueToBeExecuted = [];
let apiInProgressCheck = false;
const apiInProgressCheckFn = (data,url) => {
apiInProgressCheck = data;
if (apiInProgressCheck === true ){
queueToBeExecuted.push(url);
console.log('queue', queueToBeExecuted)
}
else {
const itemToAdd = queueToBeExecuted.shift();
console.log('shift', queueToBeExecuted)
// i have to make a api call again
}
return apiInProgressCheck;
}
const makingAnApiCall = async (url) => {
response = await axios({ url, method: get });
if (response.status) {
apiInProgressCheckFn(false, url);
if (response.status === 200 || response.status === 201) {
dispatch(success(response));
} else {
dispatch(failed(response));
}
}
};
export default makingAnApiCall;
我创建了名为“makingAnApiCall”的 JavaScript 函数,每当我调用此函数时,API 调用都会被触发,并根据响应分派(dispatch)相应的操作,并且局部变量的值也已重置。所以我无法阻止 api 被调用。任何人都可以帮助实现此 api 调用队列,并建议我使用 javascript 或使用 redux 进行 react 来实现相同目的的最佳方法吗?
最佳答案
以下是如何使用 onlyLastRequestedPromise 的示例:
const makingAnApiCall = async (url, last = x => x) => {
let response;
try {
response = await last(axios({ url, method: get }));
} catch (e) {
if (e === 'A newer request was made.') {
//ignore this error, current request replaced
// with newer one
return;
}
//something else went wrong, rethrow the error
throw e;
}
if (response.status) {
apiInProgressCheckFn(false, url);
if (
response.status === 200 ||
response.status === 201
) {
dispatch(success(response));
} else {
dispatch(failed(response));
}
}
};
//IIFE to initialize last only once
const lastSearchApiResult = (() => {
const last = onlyLastRequestedPromise('search');
return url => makingAnApiCall(url, last);
})();
关于javascript - 使用 React 和 Redux 进行 api 调用队列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58266985/