task.js (1025B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 "use strict"; 5 6 loader.lazyRequireGetter( 7 this, 8 ["executeSoon", "isAsyncFunction", "reportException"], 9 "resource://devtools/shared/DevToolsUtils.js", 10 true 11 ); 12 13 const ERROR_TYPE = (exports.ERROR_TYPE = "@@redux/middleware/task#error"); 14 15 /** 16 * A middleware that allows async thunks (async functions) to be dispatched. 17 * The middleware is called "task" for historical reasons. TODO: rename? 18 */ 19 20 function task({ dispatch, getState }) { 21 return next => action => { 22 if (isAsyncFunction(action)) { 23 return action({ dispatch, getState }).catch( 24 handleError.bind(null, dispatch) 25 ); 26 } 27 return next(action); 28 }; 29 } 30 31 function handleError(dispatch, error) { 32 executeSoon(() => { 33 reportException(ERROR_TYPE, error); 34 dispatch({ type: ERROR_TYPE, error }); 35 }); 36 } 37 38 exports.task = task;