我正在使用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