queueRunner.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.default = queueRunner;
  6. var _jestUtil = require('jest-util');
  7. var _PCancelable = _interopRequireDefault(require('./PCancelable'));
  8. var _pTimeout = _interopRequireDefault(require('./pTimeout'));
  9. function _interopRequireDefault(obj) {
  10. return obj && obj.__esModule ? obj : {default: obj};
  11. }
  12. var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
  13. var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
  14. var Promise = global[Symbol.for('jest-native-promise')] || global.Promise;
  15. function queueRunner(options) {
  16. const token = new _PCancelable.default((onCancel, resolve) => {
  17. onCancel(resolve);
  18. });
  19. const mapper = ({fn, timeout, initError = new Error()}) => {
  20. let promise = new Promise(resolve => {
  21. const next = function (...args) {
  22. const err = args[0];
  23. if (err) {
  24. options.fail.apply(null, args);
  25. }
  26. resolve();
  27. };
  28. next.fail = function (...args) {
  29. options.fail.apply(null, args);
  30. resolve();
  31. };
  32. try {
  33. fn.call(options.userContext, next);
  34. } catch (e) {
  35. options.onException(e);
  36. resolve();
  37. }
  38. });
  39. promise = Promise.race([promise, token]);
  40. if (!timeout) {
  41. return promise;
  42. }
  43. const timeoutMs = timeout();
  44. return (0, _pTimeout.default)(
  45. promise,
  46. timeoutMs,
  47. options.clearTimeout,
  48. options.setTimeout,
  49. () => {
  50. initError.message =
  51. 'Timeout - Async callback was not invoked within the ' +
  52. (0, _jestUtil.formatTime)(timeoutMs) +
  53. ' timeout specified by jest.setTimeout.';
  54. initError.stack = initError.message + initError.stack;
  55. options.onException(initError);
  56. }
  57. );
  58. };
  59. const result = options.queueableFns.reduce(
  60. (promise, fn) => promise.then(() => mapper(fn)),
  61. Promise.resolve()
  62. );
  63. return {
  64. cancel: token.cancel.bind(token),
  65. catch: result.catch.bind(result),
  66. then: result.then.bind(result)
  67. };
  68. }