在一个redux
传奇中,我向不同的系统发送了六个获取请求。我想等到所有这些请求返回,然后对结果做一些最后的处理。
为此,我有一个promises
数组,表示每个查询。我可以在数组上调用Promise.all()
,但这将导致传奇挂起,从而导致所有事件挂起,直到承诺返回。
我尝试创建一个名为async promise
的promise.all
,然后对这个承诺使用redux-effects
调用,但这也是挂起的。
在等待承诺回归的同时,我怎样才能保持我的传奇故事的async
性质?
发布于 2018-08-15 16:50:53
要并行运行所有请求,您应该使用来自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事件循环。它只会阻止生成器函数的其余部分运行。其他sagas中的其他操作和其他事件(如单击)仍将由应用程序在请求执行时接收。
有关更多信息,请参考官方文档。
发布于 2018-08-15 13:25:19
你可以做这样的事
*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
});
}
}
}
https://stackoverflow.com/questions/51859486
复制相似问题