动作创建者没有等待

时间:2019-02-03 09:39:31

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

我在应用程序中使用占位符json api来获取一些帖子及其用户。但是,用户有重复的ID,并且这些ID被多次提取。.因此,我尝试使用以下代码仅提取唯一的ID。。但是,当我通过控制台登录getState()。posts进行调试时,它显示了一个空数组,因为api是以后再叫。

我不明白的是为什么“等待”不起作用。

另外,fetchUser从未被调用,我不明白为什么。

我是Redux的新手,如果这是一个愚蠢的问题,我们感到抱歉 这是我的代码

import _ from 'lodash' ;

export const fetchEvery = () => async (dispatch, getState) => {
console.log("Before") ;
await dispatch(fetchData()) ;
console.log("After" , getState()) ;
const ids = _.uniq(_.map(getState().posts, 'userId')) ;
console.log(ids) ;
ids.forEach( id => dispatch(fetchUser(id))) ;
} ;

export const fetchData = () => dispatch => {
    let resp = {} ;

    fetch('http://jsonplaceholder.typicode.com/posts/')
    .then( res => {
            if ( res.ok )
              return res.json() ;
            else 
              throw Error(res.statusText)
          } )
    .then( res => {
            console.log(res) ;
            resp = res ;
            dispatch( {
                    type : 'FETCH_DATA' ,
                    payload : resp  
                }) ;
                    } )
    .catch( err => console.log(err) ) ;

} ;

export const fetchUser = (id) => (dispatch) => {
fetch('http://jsonplaceholder.typicode.com/users/' + id )
.then( res => {
            if ( res.ok )
              return res.json() ;
            else 
              throw Error(res.statusText)
          } )
    .then( res => {
            console.log(res) ;
            dispatch( {
                    type : 'FETCH_USER' ,
                    payload : res  
                }) ;
                    } )
    .catch( err => console.log(err) ) ;

} ;

1 个答案:

答案 0 :(得分:0)

在您的获取方法returnfetch中。目前,他们没有返回任何内容-因此没有任何保证-因此,您的await在顶层将立即解决,因为没有wait的保证。