我有一个问题,我正在使用redux thunk作为我的API中间件,当它只是更新redux状态时,它工作得很好。但是,我的部分代码要求我从请求API获得响应,而不是等待它通过redux存储。。我怎样才能“保证”这一部分?
我使用axios调用api的代码:
export async function callApi(apiRoutes, method, params) {
method = method.toUpperCase();
let apiArr = apiRoutes.split('/')
let newApiRoute = await Promise.all(apiArr.map(async (queryBreakDown, index) => {
let value
if (queryBreakDown.indexOf(':') > -1) {
queryBreakDown = queryBreakDown.replace(':', '');
if (!params) throw Error('No Params');
value = params[`${queryBreakDown}`];
delete params[`${queryBreakDown}`];
return value;
} else {
value = queryBreakDown
}
return value
}))
newApiRoute = await newApiRoute.join('/')
// NOTE: add pagination queries
if (params && params.count) {
newApiRoute += '?count=' + params.count
delete params.count
if (params.page) {
newApiRoute += '&page=' + params.page
delete params.page
}
//NOTE: add filters to query
if (params.filter) {
for (var property in params.filter) {
newApiRoute += `&filter[${property}]=` + params.filter[`${property}`]
}
delete params.filter
}
}
// NOTE: add file upload queries
if (params && params.fileType && !params.count) {
newApiRoute += '?fileType=' + params.fileType
delete params.fileType
}
let data = params ? params : null
// cookie.set('user_token', '123123123');
// cookie.remove('user_token', { path: '' });
let accessToken = cookie.get('user_token');
let headers = {};
if (accessToken) {
headers['Authorization'] = `Bearer ${accessToken}`;
}
headers['Content-Type'] = 'application/json';
const response = await axios({
method: method,
baseURL: host + '/api',
url: newApiRoute,
headers,
data
});
return response
}
我的redux thunk api中间件:
export default store => next => (action) => {
const apiRoutes = action[CALL_API];
const { method, types, params } = action;
next({ type: types[0] });
return callApi(apiRoutes, method, params).then(
response => next({
response,
type: types[1],
}), error => next({
error: (error && error.message) || 'Something bad happened',
type: types[2]
})
)
}
我需要立即从中获取返回值的函数,其中getS3UploadUrl将getS3UploadUrl分派给api中间件:
let signedURL = getS3UploadUrl({
fileType: compressedImage.type
})
但是,signedURL尚未定义。