【问题标题】:Queue for an api call using react with redux?使用与 redux 反应的 api 调用队列?
【发布时间】:2020-02-04 14:20:31
【问题描述】:

我正在处理这样一种情况,即每当我进行多个 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 调用将被触发并根据响应调度相应的操作,并且局部变量的值也已重置。所以我无法阻止 api 被调用。任何人都可以帮助实现这个 api 调用队列并建议我最好的方法,以便使用 javascript 或与 redux 做出反应来实现同样的效果?

【问题讨论】:

  • 这会使您的应用程序变慢很多,您是否要这样做,因为根据用户输入进行 api 调用而您只想解决最后一个问题?
  • 是的,基于用户输入..
  • 我不确定我是否完全理解您的问题,您是否想在执行了之前的 API 调用后找到一种方法来执行这些 API 调用?
  • 只有在用户最后输入时才能解析。也许this 可以提供帮助。

标签: javascript arrays reactjs redux axios


【解决方案1】:

这里是一个如何使用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);
})();

【讨论】:

    猜你喜欢
    • 2017-11-21
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    • 1970-01-01
    • 2011-10-28
    • 2018-05-08
    • 2016-06-12
    • 2019-10-02
    相关资源
    最近更新 更多