Skip to content
Permalink
Browse files

fix: ensure timeout is cleared in promiseTimeout

  • Loading branch information...
korhaliv committed Aug 7, 2019
1 parent f1e4d94 commit 18f13462fb59fc411860e510fd60ba3f29136ea9
Showing with 11 additions and 10 deletions.
  1. +11 −10 utils/promiseTimeout.js
@@ -3,19 +3,20 @@
*
* @param {number} ms Timeout (ms)
* @param {Promise} promise Promise to timeout
* @param {string} message messaged passed to the reject promise
* @returns {Promise} Promise that rejects in <ms> milliseconds
*/
const promiseTimeout = function(ms, promise) {
export default function(ms, promise, message = 'Timed out') {
// Create a promise that rejects in <ms> milliseconds
let timeout = new Promise((resolve, reject) => {
let id = setTimeout(() => {
clearTimeout(id)
reject(`Timed out.`)
}, ms)
})
let timerId

const timeout = new Promise((resolve, reject) => {
timerId = setTimeout(() => reject(new Error(message)), ms)
})
const clearTimer = value => {
timerId && clearTimeout(timerId)
return value
}
// Returns a race between our timeout and the passed in promise
return Promise.race([promise, timeout])
return Promise.race([promise, timeout]).then(clearTimer, clearTimer)
}

export default promiseTimeout

0 comments on commit 18f1346

Please sign in to comment.
You can’t perform that action at this time.