p_timeout.js 944 B

123456789101112131415161718192021222324252627282930313233
  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(val => {
  23. clearTimeout(timer);
  24. resolve(val);
  25. }, err => {
  26. clearTimeout(timer);
  27. reject(err);
  28. });
  29. });
  30. }