0

我正在尝试使用 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()
  ]
}
4

1 回答 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);
}

Worker saga,实际上是并行发出所有请求,并使用相关的结果数据触发成功或错误操作:

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})
  }
}
于 2016-07-21T23:18:54.777 回答