queue_runner.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = queueRunner;
  6. var _p_cancelable = require('./p_cancelable');
  7. var _p_cancelable2 = _interopRequireDefault(_p_cancelable);
  8. var _p_timeout = require('./p_timeout');
  9. var _p_timeout2 = _interopRequireDefault(_p_timeout);
  10. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11. /**
  12. * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
  13. *
  14. * This source code is licensed under the MIT license found in the
  15. * LICENSE file in the root directory of this source tree.
  16. *
  17. *
  18. */
  19. // Try getting the real promise object from the context, if available. Someone
  20. const Promise = global[Symbol.for('jest-native-promise')] || global.Promise;
  21. function queueRunner(options) {
  22. const token = new _p_cancelable2.default((onCancel, resolve) => {
  23. onCancel(resolve);
  24. });
  25. const mapper = (_ref) => {
  26. let fn = _ref.fn,
  27. timeout = _ref.timeout;
  28. let promise = new Promise(resolve => {
  29. const next = function (err) {
  30. if (err) {
  31. options.fail.apply(null, arguments);
  32. }
  33. resolve();
  34. };
  35. next.fail = function () {
  36. options.fail.apply(null, arguments);
  37. resolve();
  38. };
  39. try {
  40. fn.call(options.userContext, next);
  41. } catch (e) {
  42. options.onException(e);
  43. resolve();
  44. }
  45. });
  46. promise = Promise.race([promise, token]);
  47. if (!timeout) {
  48. return promise;
  49. }
  50. const timeoutMs = timeout();
  51. return (0, _p_timeout2.default)(promise, timeoutMs, options.clearTimeout, options.setTimeout, () => {
  52. const error = new Error('Timeout - Async callback was not invoked within the ' + timeoutMs + 'ms timeout specified by jest.setTimeout.');
  53. options.onException(error);
  54. });
  55. };
  56. const result = options.queueableFns.reduce((promise, fn) => promise.then(() => mapper(fn)), Promise.resolve());
  57. return {
  58. cancel: token.cancel.bind(token),
  59. catch: result.catch.bind(result),
  60. then: result.then.bind(result)
  61. };
  62. }