Skip to content

Instantly share code, notes, and snippets.

@neharkarvishal
Created January 7, 2023 09:05
Show Gist options
  • Save neharkarvishal/934dddbdd5743f5b80f98cd2ee2fb4c1 to your computer and use it in GitHub Desktop.
Save neharkarvishal/934dddbdd5743f5b80f98cd2ee2fb4c1 to your computer and use it in GitHub Desktop.

Revisions

  1. neharkarvishal created this gist Jan 7, 2023.
    27 changes: 27 additions & 0 deletions withTimeout.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    /**
    * Reject promise after timeout
    *
    * @todo this is slow, we should find a way to do this in a faster way
    * @param {Promise<any>} callback
    * @param {number} ms
    * @return {Promise<never>}
    */
    function withTimeout(callback, ms) {
    let timeout;

    return Promise.race([
    callback().then((result) => {
    clearTimeout(timeout);
    return result;
    }),
    new Promise((_, reject) => {
    timeout = setTimeout(() => {
    reject(new Error('timeout'));
    }, ms);
    }),
    ]);
    }

    module.exports = {
    withTimeout,
    };