Skip to content

Instantly share code, notes, and snippets.

@thadeu
Last active June 28, 2019 18:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thadeu/49fba097c98c3df467a2ea7c2ad56247 to your computer and use it in GitHub Desktop.
Save thadeu/49fba097c98c3df467a2ea7c2ad56247 to your computer and use it in GitHub Desktop.
Timeout Promise with race promises
const race = (milliseconds, ...promises) => {
  const timeout = new Promise((resolve, reject) => {
    setTimeout(() => reject(`Limit operation excedded (limit: ${milliseconds} ms)`), milliseconds)
  })

  return Promise.race([timeout, ...promises])
}

How to use?

const promise1 = setTimeout(() => new Promise((resolve, reject) => resolve('promise1')), 2000)
const promise2 = setTimeout(() => new Promise((resolve, reject) => resolve('promise2')), 3000)

race(500, promise1, promise2).catch(err => console.log(err)) // -> `Limit operation excedded (limit: 500 ms)`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment