task.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. const { Task } = require("devtools/shared/task");
  6. const { executeSoon, isGenerator, reportException } = require("devtools/shared/DevToolsUtils");
  7. const ERROR_TYPE = exports.ERROR_TYPE = "@@redux/middleware/task#error";
  8. /**
  9. * A middleware that allows generator thunks (functions) and promise
  10. * to be dispatched. If it's a generator, it is called with `dispatch`
  11. * and `getState`, allowing the action to create multiple actions (most likely
  12. * asynchronously) and yield on each. If called with a promise, calls `dispatch`
  13. * on the results.
  14. */
  15. function task({ dispatch, getState }) {
  16. return next => action => {
  17. if (isGenerator(action)) {
  18. return Task.spawn(action.bind(null, dispatch, getState))
  19. .then(null, handleError.bind(null, dispatch));
  20. }
  21. /*
  22. if (isPromise(action)) {
  23. return action.then(dispatch, handleError.bind(null, dispatch));
  24. }
  25. */
  26. return next(action);
  27. };
  28. }
  29. function handleError(dispatch, error) {
  30. executeSoon(() => {
  31. reportException(ERROR_TYPE, error);
  32. dispatch({ type: ERROR_TYPE, error });
  33. });
  34. }
  35. exports.task = task;