queue_runner.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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) {
  11. return obj && obj.__esModule ? obj : {default: obj};
  12. }
  13. /**
  14. * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
  15. *
  16. * This source code is licensed under the MIT license found in the
  17. * LICENSE file in the root directory of this source tree.
  18. *
  19. *
  20. */
  21. // Try getting the real promise object from the context, if available. Someone
  22. const Promise = global[Symbol.for('jest-native-promise')] || global.Promise;
  23. function queueRunner(options) {
  24. const token = new _p_cancelable2.default((onCancel, resolve) => {
  25. onCancel(resolve);
  26. });
  27. const mapper = _ref => {
  28. let fn = _ref.fn,
  29. timeout = _ref.timeout;
  30. var _ref$initError = _ref.initError;
  31. let initError = _ref$initError === undefined ? new Error() : _ref$initError;
  32. let promise = new Promise(resolve => {
  33. const next = function(err) {
  34. if (err) {
  35. options.fail.apply(null, arguments);
  36. }
  37. resolve();
  38. };
  39. next.fail = function() {
  40. options.fail.apply(null, arguments);
  41. resolve();
  42. };
  43. try {
  44. fn.call(options.userContext, next);
  45. } catch (e) {
  46. options.onException(e);
  47. resolve();
  48. }
  49. });
  50. promise = Promise.race([promise, token]);
  51. if (!timeout) {
  52. return promise;
  53. }
  54. const timeoutMs = timeout();
  55. return (0, _p_timeout2.default)(
  56. promise,
  57. timeoutMs,
  58. options.clearTimeout,
  59. options.setTimeout,
  60. () => {
  61. initError.message =
  62. 'Timeout - Async callback was not invoked within the ' +
  63. timeoutMs +
  64. 'ms timeout specified by jest.setTimeout.';
  65. options.onException(initError);
  66. }
  67. );
  68. };
  69. const result = options.queueableFns.reduce(
  70. (promise, fn) => promise.then(() => mapper(fn)),
  71. Promise.resolve()
  72. );
  73. return {
  74. cancel: token.cancel.bind(token),
  75. catch: result.catch.bind(result),
  76. then: result.then.bind(result)
  77. };
  78. }