我正在使用redux thunk,并且出现以下问题。 uploadClientImage
调度会为数据库创建一个图像对象并返回图像ID。Redux Thunk未按顺序调度
我在创建client_info之前需要2个图像ID。
问题是axios post到clients
被调用之前,我从2 uploadClientImage
调度检索id的。有没有办法等到这两个调度完成之前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
@azium我加了另一个函数。谢谢! – lost9123193