如何在传奇中异步加入承诺集合?



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

为此,我有一个promises数组,表示每个查询。 我可以在阵列上调用Promise.all(),但这会导致传奇挂起,从而所有事件挂起,直到承诺返回。

我尝试创建一个调用promise.allasync promise,然后在该承诺上使用redux-effectsCall,但这也挂起了。

我怎样才能在等待承诺回归的同时保持我传奇的async性质?

要并行运行所有请求,您应该使用redux-saga中的all效果。 它类似于您已经引用的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 事件循环。 它只会阻止生成器函数的其余部分运行。 当请求正在进行时,应用程序仍将收到其他 saga 中的其他操作和其他事件(例如单击(。

有关详细信息,请参阅官方文档。

你可以做这样的事情

*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
});
}
}
}

最新更新