2016-09-23 39 views
1

我正在使用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"); 
    }); 
    } 
} 
+0

可能'uploadClientImage'有些異步。如果你發佈這個函數,我們可能會給你一些具體的建議,但通常你需要一個承諾或回調函數。 (如果你也使用axios,你可能已經有了承諾) – azium

+0

@azium我加了另一個函數。謝謝! – lost9123193

回答

1

我不認爲uploadClientImage需要是Redux的動作,因爲你沒有任何調度。它應該只是一個返回承諾的常規函數​​。我重構了一下你的代碼(沒有測試它)。

export function uploadClientImage(image_file) { 
    var formData = new FormData(); 
    for (var key in image_file) { 
     formData.append(key, image_file[key]); 
    } 
    console.log(formData); 
    // return the promise axios creates 
    return 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 photo = client_info.photo_id[0]; 
    // upload both images at the same time, continue when both are done 
    Promise.all([uploadClientImage(logo), uploadClientImage(photo)]) 
    .then(function(results){ 
     client_info["photo_id"] = results[0]; 
     client_info["logo_id"] = results[1]; 

     return axios.post(`${API_URL}/clients`, client_info, {withCredentials: true}) 
    }) 
    .then(response => { 

     //...... 
    }) 
    .catch(() => { 
     console.log("Can't create client"); 
    }); 
    } 
} 
+0

您好Tim,我試過這個,我在返回image_id和另一個console.log結果之前添加了一個console.log()。結果會在image_id之前打印出來。所以我想我仍然有一個奇怪的異步問題-EDIT我忘了採取REDX行動我會再試試這個 – lost9123193

+0

我試過解決方案,我認爲該行動是必要的,因爲我得到的錯誤操作必須是純對象。使用自定義中間件進行異步操作。當我不添加功能調度 – lost9123193