Created
February 28, 2021 05:48
-
-
Save javascripto/f8f438b8993319efe5a5ca8a4390cbc3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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