gpt4 book ai didi

reactjs - Redux saga、axios 和进度事件

转载 作者:行者123 更新时间:2023-12-03 13:40:41 25 4
gpt4 key购买 nike

是否有干净/简短/正确的方法来一起使用 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 });
}
}

我想接收进度事件并将其放在 saga 中。我还想捕获 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);
}

在saga中,我们需要创建eventChannel,但将emit放在外面。

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 saga、axios 和进度事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40402744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com