davidraviv
2/15/2017 - 9:14 AM

Execute a Promise with a timeout. If the timeout occurs before completing the Promise, it should reject.

Execute a Promise with a timeout. If the timeout occurs before completing the Promise, it should reject.

/**
 * Accepts a promise and a timeout. If the timeout reached while the promise is stil pending, it rejects with a timeout.
 * @param timeout in milli
 * @param promise
 */
Promise.timeout = (timeout, promise) => {
    let bombId;
    Promise.race([
        promise,
        new Promise((resolve, reject) => {
            bombId = setTimeout( (timeoutx) => {
                return reject('Timeout');
            }, timeout, timeout);
        })
    ]).then(res => {
        return Promise.resolve(res)
    })
        .catch(err => {
            return Promise.reject(err)
        })
        .finally(() => {
            if (bombId) {
                clearTimeout(bombId);
            }
        })
};


//Usage
usage = () => {
  
  // define the promise to be performed in a due time
  let handle = new Promise(function (resolve, reject) {
    // ... some logic goes here ...
    return resolve();
  });
  
  // execute the promise with a timeout of 10 seconds
  return Promise.timeout(10000, handle);
}