Created
August 2, 2020 13:27
-
-
Save XoseLluis/5c2e912b74fc2f670a226254705df3a2 to your computer and use it in GitHub Desktop.
Retry and async function (a function that returns a Promise)
This file contains 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
//wrap setTimeout with an async-await friendly function | |
function sleep(ms){ | |
console.log("sleep starts"); | |
let resolveFn; | |
let pr = new Promise(res => resolveFn = res); | |
setTimeout(() => { | |
console.log("sleep ends"); | |
resolveFn(); | |
}, ms); | |
return pr; | |
} | |
//fn: function returning a Promise | |
//if the Promise is rejected we'll retry up to "attempts" times, with a "timeout" in between | |
//returns a new function with retry logic | |
function addRetryToAsyncFn(fn, attempts, timeout){ | |
return async (...args) => { | |
while (attempts--){ | |
try{ | |
return await fn(...args); | |
} | |
catch(ex){ | |
console.log("attempt failed"); | |
if (!attempts) | |
throw ex; | |
} | |
await sleep(timeout); | |
} | |
}; | |
} | |
//test code: | |
class TicketsProvider{ | |
constructor(){ | |
this.requestsCounter = 1; | |
} | |
//we give a ticket out of 3 requests | |
getTicketAsync(){ | |
return new Promise((res, rej) => { | |
setTimeout(()=> { | |
if (this.requestsCounter++ % 3 === 0) | |
res({ticketId: (this.requestsCounter - 1) / 3}); | |
else | |
res(null); | |
}, 1000); | |
}); | |
} | |
} | |
var ticketsProvider = new TicketsProvider(); | |
async function getAndFormatNextTicket(user){ | |
//console.log("inside getAndFormatNextTicket"); | |
let ticket = await ticketsProvider.getTicketAsync(); | |
if (ticket === null) | |
throw new Error("no ticket available"); | |
else | |
return `[${ticket.ticketId} - ${user}]`; | |
} | |
//async main | |
(async () => { | |
try{ | |
let formattedTicket = await addRetryToAsyncFn(getAndFormatNextTicket, 5, 1000)("Francois"); | |
console.log(`formattedTicket: ${formattedTicket}`); | |
formattedTicket = await addRetryToAsyncFn(getAndFormatNextTicket, 2, 1000)("Francois"); | |
console.log(`formattedTicket: ${formattedTicket}`); | |
} | |
catch(ex){ | |
console.log("Exception: " + ex.message); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment