Skip to content

Instantly share code, notes, and snippets.

@javascripto
Created February 28, 2021 05:48
Show Gist options
  • Select an option

  • Save javascripto/f8f438b8993319efe5a5ca8a4390cbc3 to your computer and use it in GitHub Desktop.

Select an option

Save javascripto/f8f438b8993319efe5a5ca8a4390cbc3 to your computer and use it in GitHub Desktop.
const future = Date.now() + 3000
const fakeApi = {
async getResult() {
if (Date.now() >= future) {
return { foo: 'bar' }
}
return {}
}
}
const wait = (miliseconds) => new Promise(resolve => setTimeout(resolve, miliseconds))
async function retryPromise({ times, interval, promise, resolveCondition }) {
if (times === 0) {
throw new Error('Numero de tentativas excedido')
}
const response = await promise()
if (resolveCondition(response)) {
return response
}
console.log('[Falhou] - Tentando novamente')
await wait(interval)
return retryPromise({ times: times - 1, promise, resolveCondition, interval })
}
async function getResult() {
const result = await retryPromise({
promise: () => fakeApi.getResult(),
times: 7,
interval: 500,
resolveCondition: (response) => response.foo
})
return result
}
getResult()
.then(console.log)
.catch(e => console.log(`[Erro]: ${e.message}`))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment