我正在尝试使用redux saga在我加载页面的同时进行异步调用...但只调用了loadPositions()。有谁知道为什么?我认为这与竞争条件有关。请纠正我。
const fetchPositions = () => {
return fetch(POSITIONS_API_ENDPOINT).then(function (response) {
return response.json().then(function (results) {
return results.map(function (p) {
return {
position: p.position,
platformId: p.platform_id
}
})
})
})
};
const fetchBanners = () => {
return fetch(BANNER_API_ENDPOINT).then(function (response) {
return response.json().then(function (results) {
return results.map(function (p) {
console.log(p)
return {
banner_id: p.banner_id,
type: p.image.type,
width: p.image.width
}
})
})
})
};
export function* loadBanners() {
try {
const banners = yield call(fetchBanners);
yield put({type: "BANNERS_LOADED", banners})
} catch (error) {
yield put({type: "BANNERS_LOAD_FAILURE", error: error})
}
}
export function* loadPositions() {
try {
const positions = yield call(fetchPositions);
yield put({type: "POSITIONS_LOADED", positions})
} catch (error) {
yield put({type: "POSITION_LOAD_FAILURE", error: error})
}
}
export function* rootSaga() {
yield [
loadBanners(),
loadPositions()
]
}
答案 0 :(得分:0)
试试这个:
ON_LOAD_START
操作yield []
语法并行处理所有请求,并使用结果数据触发相应的操作。Root saga,撰写你的所有传奇:
export default function* rootSaga() {
yield fork(watchOnLoad);
}
Watcher saga,在踢出工人传奇之前等待行动ON_LOAD_START
:
function* watchOnLoad() {
// takeLatest will not start onLoad until an action with type
// ON_LOAD_START has been fired.
yield* takeLatest("ON_LOAD_START", onLoad);
}
工作人员传奇,实际上是并行处理所有请求并使用相关结果数据触发成功或错误操作:
export function* onLoad() {
try {
const [banners, positions] = yield [
call(fetchBanners),
call(fetchPositions)
]
yield put({type: "ON_LOAD_SUCCESS", banners, positions})
} catch (error) {
yield put({type: "ON_LOAD_ERROR", error})
}
}