使用 redux-api-middleware 处理图片/jpeg 内容 [英] Using redux-api-middleware to process image/jpeg content
问题描述
我有一个 RSAA(Redux 标准 API 调用操作),我用来检索 image/jpeg
内容.我见过的所有示例都处理 JSON 数据,因此我复制了 getJSON
函数并实现了我自己的 getImage
函数来处理这种内容类型.我现在遇到的问题是这个 blob 需要转换为 base64,并且必须使用异步函数来完成.因此,我的 FSA 在此异步操作完成之前被触发.
I have an RSAA (Redux Standard API-calling Action) that I'm using to retrieve image/jpeg
content. All the examples I've seen deal with JSON data so I copied the getJSON
function and implemented my own getImage
function to deal with this content type. The problem I'm now running into is that this blob needs to be converted to base64 and that has to be done using an async function. So, my FSA gets triggered before this async operation completes.
我怀疑我需要在 RSAA payload
处理中以某种方式捎带现有的承诺链,但我不知道如何做到这一点.
I suspect that I need to somehow piggyback on the existing promise chain in the RSAA payload
processing but I'm not sure how to do this.
这是我需要执行承诺 resolve
以返回此结果的行注释的代码片段:
Here's the snippet of code with the line commented where I need to perform the promise resolve
to return this result:
export function fetchSiteThumbnailImage(endpoint) {
return {
[CALL_API]: {
endpoint,
method: 'GET',
headers: {
'Accept': 'image/jpeg'
},
types: [
LOAD_SITE_THUMBNAIL_REQUEST,
{
type: LOAD_SITE_THUMBNAIL_SUCCESS,
payload: (action, state, res) => {
return getImage(res).then((blob) => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = () => {
const base64data = reader.result;
return base64data; // this needs to "resolve" - how??
}
});
},
meta: (action, state, res) => {
return {
siteId,
endpoint
}
}
},
LOAD_SITE_THUMBNAIL_FAILURE
]
}
}
}
谢谢!
推荐答案
您必须将 FileReader
逻辑包装到 Promise
中:
You have to wrap your FileReader
logic into a Promise
:
function readAsBase64(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
const base64data = reader.result;
resolve(base64data);
}
reader.onerror = (err) => {
reject(err);
}
reader.readAsDataURL(blob);
});
}
你的 payload
函数可以是
(action, state, res) => getImage(res).then(readAsBase64);
一些注意事项:
reader.onloadend
在读取操作完成(成功或失败)时调用,而reader.onload
仅在成功完成时调用和reader.onerror
仅在失败完成时 —你想把这两种情况分开.
reader.onloadend
gets called when the reading operation is completed (either in success or in failure), whilereader.onload
is called only on successful completion andreader.onerror
only on failed completion — you want to separate the two cases.
您应该在开始读取 blob 之前设置事件处理程序以避免竞争条件 —所以把 reader.readAsDataURL
放在最后.
You should set the event handlers before you start reading the blob to avoid race conditions — so put reader.readAsDataURL
at the end.
这篇关于使用 redux-api-middleware 处理图片/jpeg 内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!