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.ts 1.2KB

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