【问题标题】:calling an api request multiple times sequentially using redux-saga使用 redux-saga 顺序多次调用 api 请求
【发布时间】:2021-02-17 11:18:55
【问题描述】:

我需要在我的 reactjs 应用程序中多次调用 API 请求(具有不同的请求负载)。但是,我不想同时调用这些多个请求,我想等到一个完成,然后再调用另一个,以便按顺序调用它们。如何使用 redux-saga 做到这一点?

这是我为这个特定 api 实现我的传奇的方式,但我不知道如何修改它以按照我上面解释的方式工作:

export function* fetchChartData(action) {
    const call = Effect.call;
    const put = Effect.put;
    try {
        const response = yield call(chartApi.GetCharts, action.payload)
        yield put({
            type: ActionChartDataType.GET_CHART_DATA_SUCCESS,
            payload: response.data.data
        })
    } catch (e) {

    }
}

export function* getAllCharts() {
    yield takeEvery(ActionChartDataType.GET_CHART_DATA_START, fetchChartData)
}

其实我需要有GET_CHART_DATA_SUCCESS的动作,然后调用其他的GET_CHART_DATA_START。非常感谢任何帮助。

【问题讨论】:

  • 所以你想限制chartApi.GetCharts 只允许一个活动请求,无论你在特定时间内调用多少次?
  • 感谢您的评论。是的,我希望在某个时间有一个活动请求,并且只要前一个请求得到响应,就会调用其他请求,以便依次调用它们。

标签: reactjs react-redux redux-saga


【解决方案1】:

这是一个如何按照您描述的方式对承诺返回函数进行分组的示例:

const group = (promiseFunction) => {
  let promise = Promise.resolve();
  return (...args) => {
    promise = promise
      .catch(() => 'ignore')
      .then(() => promiseFunction(...args));
    return promise;
  };
};

//a helper that returns a promise that resolves in one second
const later = (value) =>
  new Promise((r) => setTimeout(() => r(value), 1000));
//promise returning function that returns passed argument a second later
const promiseFn = (value) => {
  console.log('promiseFn called with', value);
  return later(value).then((r) =>
    r === 3 ? Promise.reject(r) : r
  );
};
//grouped primiseFn
const groupedPromiseFn = group(promiseFn);
//test calling the grouped promise function
[1, 2, 3, 4, 5].forEach(
  (value) =>
    console.log('calling grouped with', value) ||
    groupedPromiseFn(value).then(
      (r) => console.log('resolved with:', r),
      (r) => console.log('rejected with:', r)
    )
);

您可以使用groupchartApi.GetCharts 以您想要的方式运行:

const groupedGetCharts = group(chartApi.GetCharts)
//later in your code:
const response = yield call(groupedGetCharts, action.payload)

【讨论】: