如何在 Saga 中异步加入 Promises 集合?

How to join a collection of Promises asyncrounously in a Saga?

redux saga 中,我向不同的系统发送了六个获取请求。我想等到所有这些请求 return,然后对结果进行一些最终处理。

为此,我有一个 promises 数组,代表每个查询。我可以在数组上调用 Promise.all(),但这会导致 saga 挂起,因此所有事件都会挂起,直到承诺 return.

我尝试创建一个名为 promise.allasync promise,然后根据该承诺使用 redux-effects 调用,但这也挂起。

如何在等待对 return 的承诺时保持我传奇的 async 性质?

你可以这样做

*getProductsSaga() {
    while (true) {
      yield take(types.GET_PRODUCTS_REQUEST);
      try {
        const result1 = yield call(() => getProducts1Promise());
        const result2 = yield call(() => getProducts2Promise());
        const result3 = yield call(() => getProducts3Promise());
        const result4 = yield call(() => getProducts4Promise());
        yield put({
          type: types.GET_PRODUCTS_SUCCESS,
          payload: [result1, result2, result3, result4] // process/combine results depending on how you want
        });
      } catch (error) {
        yield put({
          type: types.GET_PRODUCTS_FAILURE,
          payload: error
        });
      }
    }
  }

为了 运行 所有并行请求,您应该使用 redux-sagaall 效果。它类似于您已经引用的 Promise.all 方法。

示例:

import { fetchCustomers, fetchProducts } from './path/to/api'
import { all, call } from `redux-saga/effects`

function* mySaga() {
  const { customers, products } = yield all({
    customers: call(fetchCustomers),
    products: call(fetchProducts)
  });
  // do something with results
}

这是运行并行异步操作并等待所有进程完成的最直接方法。这种方法 不会 阻塞 javascript 事件循环。它只会阻止来自 运行ning 的生成器函数的其余部分。其他 sagas 中的其他操作和其他事件(例如点击)在请求进行期间仍会被您的应用程序接收。

详情请参考官方docs