2016-09-23 38 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