2016-03-15 52 views
0

如何处理和承诺进度?Redux和承诺进度

我想在promise执行时显示一些旋转杆或其他东西,我使用axios来处理请求,但他们有一个API来处理在请求的配置对象中这样的进程:

{ 
    progress: function(progressEvent) { 
     // Do whatever you want with the native progress event 
    } 
} 

但我只能发送一个终极版动作要求,如:

return { 
    type: "HTTP_REQUEST", 
    payload: axios.get("/webAPI/data", configObj) 
} 

我如何处理与这些条件的进展情况?

回答

0

如果您正在查看只显示微调器而不是进度条,那么您确实不需要进度功能。相反我会推荐一些沿着这些路线:

const axiosAction = function(configObj) { 
    // We have to thunk the dispatch since this is async - need to use the thunk middleware for this type of construct 
    return dispatch => { 
    /* action to notify the spinner to start (ie, update your store to have a 
    loading property set to true that will presentationally start the spinner) */ 
    dispatch({ 
     type: 'AXIOS_REQUEST_STARTING' 
    }); 
    return axios.get("/webAPI/data", configObj) 
     .then(res => { 
      /* action to set loading to false to stop the spinner, and do something with the res */ 
      return dispatch({ 
      type: 'AXIOS_REQUEST_FINISHED', 
      payload: res, 
      }) 
     }) 
     .catch(err => /* some error handling*/); 
    }; 
} 

编辑添加链接redux-thunk

2

虽然gabdallah的答案是正确的,我觉得它只是部分地回答了这个问题。如果你愿意,这两个答案中的代码可以很容易地结合起来。

如果你想要向用户显示进度,你可以调度进度回调中的特定进度动作,并将当前进度作为有效负载。事情是这样的:

{ 
    progress: function(progressEvent) { 
     return dispatch({ 
      type: "HTTP_REQUEST_PROGRESS", 
      payload: { 
       url: "/webAPI/data", 
       currentBytes: progressEvent.current, 
       totalBytes: progressEvent.total // properties on progressEvent made up by yours truly 
      } 
     }); 
    } 
} 

在本质上,你只需要代表request progress,就像你已经发起一个请求(也可能一个两个成功的和不成功的结果)的动作与另一动作。