gpt4 book ai didi

javascript - Redux-Saga 非ajax相关的回调问题

转载 作者:行者123 更新时间:2023-11-29 21:14:08 30 4
gpt4 key购买 nike

所以,我很难弄清楚如何转换以下 example使用 sagas 作为它不是 ajax 相关的异步问题:

var dogBarkingBuffer = null;
// Fix up prefixing
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();

function loadDogSound(url) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';

// Decode asynchronously
request.onload = function() {
context.decodeAudioData(request.response, function(buffer) {
dogBarkingBuffer = buffer;
}, onError);
}
request.send();
}

我发现的问题不是 XMLHttpRequest 相关的东西,而是如何处理 decodeAudioData(data, callback)仅通过回调为您提供返回的数据,因此我想触发一个操作,将其添加到我的 Redux 存储中。

目前我的 saga 看起来像这样,但是 decodeAudio 前面缺少的 yield 似乎是个问题:

import { takeLatest } from "redux-saga";
import { call, put } from "redux-saga/effects";
import axios from "axios";

import * as acts from "actions/playList";


const audioFileRequest = (url) => {
return axios.get(url, {
withCredentials: true,
responseType: "arraybuffer",
})
.then(({ data }) => data)
.catch(({ error }) => error);
};

const decodeAudio = (undecodedData, audioContext) => {
return audioContext.decodeAudioData(undecodedData, (buffer) => {
acts.recivedAudioFile(buffer); // no yeald ???
});
};

function *fetchAudio({ url, audioContext }) {
try {
let rawAudioData = yield call(audioFileRequest, url);
decodeAudio(rawAudioData, audioContext); // no yield ???
}
catch (error) {
yield put(acts.errorFetchingAudioFile(error));
}
}

export function *watchFetchAudio() {
yield takeLatest(acts.AUDIO_FILE_REQUEST, fetchAudio);
}

最佳答案

我认为你可以使用 es6-promise 转换解码音频函数并使用 redux saga 调用方法。

const decodeAudio = ({rawAudioData, audioContext}) => {
return new Promise((resolve, reject) => {
audioContext.decodeAudioData(rawAudioData, (buffer) => {
resolve({buffer}); // or reject if failed
});
}).then(({buffer}) => buffer).catch(error => error)
};

function *fetchAudio({ url, audioContext }) {
try {
let rawAudioData = yield call(audioFileRequest, url);
let buffer = yield call(decodeAudio, {rawAudioData, audioContext});
acts.recivedAudioFile(buffer);
}
catch (error) {
yield put(acts.errorFetchingAudioFile(error));
}
}

关于javascript - Redux-Saga 非ajax相关的回调问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40221362/

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