Skip to content
This repository has been archived by the owner on Nov 17, 2023. It is now read-only.

Commit

Permalink
fix: ensure timeout is cleared in promiseTimeout
Browse files Browse the repository at this point in the history
  • Loading branch information
korhaliv committed Aug 8, 2019
1 parent f1e4d94 commit 18f1346
Showing 1 changed file with 11 additions and 10 deletions.
21 changes: 11 additions & 10 deletions utils/promiseTimeout.js
Expand Up @@ -3,19 +3,20 @@
* *
* @param {number} ms Timeout (ms) * @param {number} ms Timeout (ms)
* @param {Promise} promise Promise to timeout * @param {Promise} promise Promise to timeout
* @param {string} message messaged passed to the reject promise
* @returns {Promise} Promise that rejects in <ms> milliseconds * @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 // Create a promise that rejects in <ms> milliseconds
let timeout = new Promise((resolve, reject) => { let timerId
let id = setTimeout(() => {
clearTimeout(id)
reject(`Timed out.`)
}, ms)
})


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 // 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.