p_timeout.js 974 B

12345678910111213141516171819202122232425262728293031323334353637
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.default = pTimeout;
  6. /**
  7. * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
  8. *
  9. * This source code is licensed under the MIT license found in the
  10. * LICENSE file in the root directory of this source tree.
  11. *
  12. *
  13. */
  14. // Try getting the real promise object from the context, if available. Someone
  15. // could have overridden it in a test.
  16. const Promise = global[Symbol.for('jest-native-promise')] || global.Promise;
  17. // A specialized version of `p-timeout` that does not touch globals.
  18. // It does not throw on timeout.
  19. function pTimeout(promise, ms, clearTimeout, setTimeout, onTimeout) {
  20. return new Promise((resolve, reject) => {
  21. const timer = setTimeout(() => resolve(onTimeout()), ms);
  22. promise.then(
  23. val => {
  24. clearTimeout(timer);
  25. resolve(val);
  26. },
  27. err => {
  28. clearTimeout(timer);
  29. reject(err);
  30. }
  31. );
  32. });
  33. }