Redux thunk-嵌套调度的功能/动作

时间:2019-11-10 22:47:39

标签: javascript reactjs redux react-redux redux-thunk

我正在使用redux-thunk在我的react应用中执行异步操作,如下所示:

export const fetchImages = (objects) => dispatch => {
   const promises = objects.map(obj => axios
       .get(`${API_URL}/files/${obj.img ? vendor.img : 'default.png'}`, {responseType: 'arraybuffer'})
       .then( res => obj.imgData = 'data:;base64,' + convertArrayBufferToBase64(res.data))
   );
   return Promise.all(promises).then (() => Promise.resolve(objects));
}

当我在任何组件中使用它时,它都可以正常工作。但是,如果我将其用于其他操作,例如:

export const fetchAllObjects = () => dispatch => axios.get(`${API_URL}/objects?limit=50`)
   .then(res => fetchImages(res.data.docs).then(objects => 
       dispatch({
           type: FETCH_ALL_OBJECTS,
           payload: objects
       });
   ));

失败。我希望它返回一个promise,但是它返回“ dispatch => ...”,因此then()在返回的值上失败。

1 个答案:

答案 0 :(得分:1)

我刚刚注意到fetchImages是一个返回函数的函数:

export const fetchAllObjects = () => dispatch => axios.get(`${API_URL}/objects?limit=50`)
   .then(res => fetchImages(res.data.docs)(dispatch).then(objects => 
       dispatch({
           type: FETCH_ALL_OBJECTS,
           payload: objects
       });
   ));