Redux Thunk不按顺序调度动作

时间:2016-09-23 22:19:44

标签: reactjs asynchronous redux redux-thunk

我正在使用redux thunk,我有以下问题。 uploadClientImage调度为数据库创建一个图像对象并返回图像ID。

在创建client_info之前,我需要2个图像ID。

问题是在我从2 clients个调度中检索id之前调用uploadClientImage的axios帖子。有没有办法等到在axios post请求之前完成这2个调度之后叫什么名字?

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");
    });
  }
}

1 个答案:

答案 0 :(得分: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");
    });
  }
}