是否可以使用干净/简短/正确的方式来一起使用axios Promise和上载进度事件?

假设我具有下一个上传功能:

function upload(payload, onProgress) {
  const url = '/sources/upload';

  const data = new FormData();

  data.append('source', payload.file, payload.file.name);

  const config = {
    onUploadProgress: onProgress,
    withCredentials: true
  };

  return axios.post(url, data, config);
}

该函数返回了promise。

我也有一个传奇:
function* uploadSaga(action) {
  try {
    const response = yield call(upload, payload, [?? anyProgressFunction ??]);
    yield put({ type: UPLOADING_SUCCESS, payload: response });
  } catch (err) {
    yield put({ type: UPLOADING_FAIL, payload: err });
  }
}

我想接收进度事件,并通过佐贺来说明。我也想捕获axios请求的成功(或失败)结果。是否可以?

谢谢。

最佳答案

因此,我找到了答案,感谢Mateusz Burzyński的澄清。

我们需要使用eventChannel,但要谨慎一点。

假设我们有用于上传文件的api函数:

function upload(payload, onProgress) {
  const url = '/sources/upload';

  const data = new FormData();

  data.append('source', payload.file, payload.file.name);

  const config = {
    onUploadProgress: onProgress,
    withCredentials: true
  };

  return axios.post(url, data, config);
}

在传奇中,我们需要创建eventChannel,但将外部放出。
function createUploader(payload) {

  let emit;
  const chan = eventEmitter(emitter => {

    emit = emitter;
    return () => {}; // it's necessarily. event channel should
                     // return unsubscribe function. In our case
                     // it's empty function
  });

  const uploadPromise = upload(payload, (event) => {
    if (event.loaded.total === 1) {
      emit(END);
    }

    emit(event.loaded.total);
  });

  return [ uploadPromise, chan ];
}

function* watchOnProgress(chan) {
  while (true) {
    const data = yield take(chan);
    yield put({ type: 'PROGRESS', payload: data });
  }
}

function* uploadSource(action) {
  const [ uploadPromise, chan ] = createUploader(action.payload);
  yield fork(watchOnProgress, chan);

  try {
    const result = yield call(() => uploadPromise);
    put({ type: 'SUCCESS', payload: result });
  } catch (err) {
    put({ type: 'ERROR', payload: err });
  }
}

关于reactjs - Redux传奇,Axios和进度事件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40402744/

10-12 02:06