Redux saga不会同时触发两个异步调用

问题描述 投票:0回答:1

我正在尝试使用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()
  ]
}
redux redux-saga
1个回答
0
投票

试试这个:

  • 通过触发ON_LOAD_START动作开始初始并行加载
  • 使用yield []语法并行处理所有请求,并使用结果数据触发相应的操作。

根传奇,组成你所有的传奇:

export default function* rootSaga() {
  yield fork(watchOnLoad);
}

看守传奇,在踢工人传奇之前等待行动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})
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.