You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

timeoutPromise.js 1.2KB

123456789101112131415161718192021222324252627282930313233343536
  1. // @flow
  2. /**
  3. * Returns a new {@code Promise} which settles when a specific {@code Promise}
  4. * settles and is automatically rejected if the specified {@code Promise}
  5. * doesn't settle within a specific time interval.
  6. *
  7. * @param {Promise} promise - The {@code Promise} for which automatic rejecting
  8. * after the specified timeout is to be implemented.
  9. * @param {number} timeout - The number of milliseconds to wait the specified
  10. * {@code promise} to settle before automatically rejecting the returned
  11. * {@code Promise}.
  12. * @returns {Promise} - A new {@code Promise} which settles when the specified
  13. * {@code promise} settles and is automatically rejected after {@code timeout}
  14. * milliseconds.
  15. */
  16. export function timeoutPromise<T>(
  17. promise: Promise<T>,
  18. timeout: number
  19. ): Promise<T> {
  20. return new Promise((resolve, reject) => {
  21. const timeoutID
  22. = setTimeout(() => reject(new Error('timeout')), timeout);
  23. promise.then(
  24. /* onFulfilled */ value => {
  25. resolve(value);
  26. clearTimeout(timeoutID);
  27. },
  28. /* onRejected */ reason => {
  29. reject(reason);
  30. clearTimeout(timeoutID);
  31. }
  32. );
  33. });
  34. }