【发布时间】:2017-02-01 21:04:46
【问题描述】:
我正在使用 redux thunk,但遇到以下问题。
uploadClientImage 调度向数据库创建一个图像对象并返回图像 ID。
在创建 client_info 之前,我需要 2 个图像 ID。
问题是在我从 2 个uploadClientImage 调度中检索 id 之前调用了到clients 的 axios 帖子。有没有办法等到这 2 个调度完成后再调用 axios 帖子请求?
action.js
export function uploadClientImage(image_file) {
return function(dispatch) {
var formData = new FormData();
for (var key in image_file) {
formData.append(key, image_file[key]);
}
console.log(formData);
axios.post(`${API_URL}/photos`, formData, {withCredentials: true, headers: {'Content-Type': 'multipart/form-data'}})
.then(response => {
var image_id = response.data.id;
return image_id;
})
.catch(() => {
console.log("Can't fileUpload");
});
}
}
export function createClient(client_info, logo, photo) {
return function(dispatch) {
var logo = client_info.logo_id[0];
var logo_id= dispatch(uploadClientImage(logo);
var photo = client_info.photo_id[0];
var photo_id = dispatch(uploadClientImage(photo));
client_info["photo_id"] = photo_id;
client_info["logo_id"] = logo_id;
axios.post(`${API_URL}/clients`, client_info, {withCredentials: true})
.then(response => {
//......
})
.catch(() => {
console.log("Can't create client");
});
}
}
【问题讨论】:
-
可能
uploadClientImage做了一些异步操作。如果您发布该函数,我们可能会给您具体的建议,但通常您需要一个承诺或回调函数。 (如果你也在使用 axios,你可能已经有了一个承诺) -
@azium 我添加了其他功能。谢谢!
标签: reactjs asynchronous redux redux-thunk