All files timeout.js

100% Statements 7/7
100% Branches 2/2
100% Functions 3/3
100% Lines 7/7

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23                          1x 3x 3x 2x   3x 1x 1x    
/**
 * Executes an async functions but will throw an error
 * if not complete in a certain amount of time
 *
 * @async
 * @function timeout
 * @param  {function} func - The async function to execute
 * @param  {string} [label='Timeout'] - The text for the error message
 * @param  {number} [time=100] - The duration in milliseconds
 *
 * @example
 * await timeout(() => asyncFunc(1), 'My Async Function', 20)
 */
module.exports = async (func, label = 'Timeout', time = 100) =>
  new Promise(async (resolve, reject) => {
    const timer = setTimeout(() => {
      return reject(new Error(`Timeout Error: ${label}`))
    }, time)
    const result = await func()
    clearTimeout(timer)
    return resolve(result)
  })