2016-05-30 197 views
0

我正在嘗試設置redux,react-redux和redux-thunk。認爲一般情況不錯,但是我有一個關於將多個異步操作鏈接在一起時應該看起來如何的問題。Redux連接異步操作

具體而言,我有一個場景,可以單獨或間接地調用可以調用它們的另一個動作。我的問題是,如果我想成爲慣用語,應該如何編寫selectItem

action.js

export function fetchByContext(contextId) { 
    return dispatch => { 
     _fetchByContext(messages => { 
      dispatch({ type: RECEIVE_MESSAGES, ... }); 
     }); 
    }; 
}; 

export function subscribeByContext(contextId) { 
    return dispatch => { 
     _subscribeByContext(messages => { 
      dispatch({ type: RECEIVE_MESSAGES, ... }); 
     }); 
    }; 
}; 

export function selectItem(contextId) { 
    return dispatch => { 
     subscribeByContext(contextId)(dispatch); 
     fetchByContext(contextId)(dispatch); 
    }; 
}; 
+0

異步,等待keywork也許可以幫助 –

回答

0

我認爲最關鍵的是(ref):

從內部功能的返回值將作爲調度本身

的返回值

如果fetchByContext(),的內部函數返回一個承諾,這些可以串聯或從selectItem()並行運行。一個未經考驗的實現,假設既不_fetchByContext()也不_subscribeByContext()回報承諾是:

export function fetchByContext(contextId) { 
    return dispatch => { 
     return new Promise((resolve, reject) => { 
      _fetchByContext(messages => { 
       dispatch({ type: RECEIVE_MESSAGES, ... }); 
       resolve(messages); 
      }); 
     }); 
    }; 
}; 

export function subscribeByContext(contextId) { 
    return dispatch => { 
     return new Promise((resolve, reject) => { 
      _subscribeByContext(messages => { 
       dispatch({ type: RECEIVE_MESSAGES, ... }); 
       resolve(messages); 
      }); 
     }); 
    }; 
}; 

export function selectItem(contextId) { 
    return dispatch => { 
     // CALL IN SERIES 
     return dispatch(subscribeByContext(contextId)) 
      .then(() => dispatch(fetchByContext(contextId))); 
     // CALL IN PARALLEL (alternative to the code above; this is probably not what you want - just keeping for reference) 
     return Promise.all(
      dispatch(subscribeByContext(contextId)), 
      dispatch(fetchByContext(contextId)) 
     ); 
    }; 
} 

再次請注意上面的代碼是未經測試,只是給予了一般的解決方案的想法希望。