Skip to content

Instantly share code, notes, and snippets.

@michaelwclark
Last active August 2, 2018 20:20
Show Gist options
  • Select an option

  • Save michaelwclark/4f9e450d2a3570ff5cc7eb88949ca47b to your computer and use it in GitHub Desktop.

Select an option

Save michaelwclark/4f9e450d2a3570ff5cc7eb88949ca47b to your computer and use it in GitHub Desktop.
Examples of Async await retry
const ac = promise => promise.then(data => [null, data]).catch(err => [err])
const timeout = ms => new Promise(resolve => setTimeout(resolve, ms*1000))
const acFailRetry = asyncFn => async (...params) => {
const retryBlock = async (retry=0, errs=[]) => {
if(retry > 3)
throw errs
const [err, resp] = await ac(asyncFn(...params))
if(err) {
await timeout(retry)
return await retryBlock(retry+1, errs.concat(err))
}
return resp
}
return await retryBlock()
}
let x = -4
const failFn = async (y,z) => {
if(x!==2)
throw `Error x:${++x}, ${y}, ${z}`
return `success! ${x} ${y} ${z}`
}
const run = async() => await acFailRetry(failFn)('fake', 'params')
run()
.then(_=>console.log('res',_))
.catch(_=>console.log('err', _))
const ac = promise => promise.then(data => [null, data]).catch(err => [err])
const timeout = ms => new Promise(resolve => setTimeout(resolve, ms*1000))
const acFailRetry = asyncFn => async (...params) => {
const retryBlock = async (retry=0, errs=[]) => {
if(retry > 3)
throw errs
const [err, resp] = await ac(asyncFn(...params))
if(err) {
await timeout(retry)
return await retryBlock(retry+1, errs.concat(err))
}
return resp
}
return await retryBlock()
}
let x = 0
const failFn = async (y,z) => {
if(x!==2)
throw `Error x:${++x}, ${y}, ${z}`
return `success! ${x} ${y} ${z}`
}
const run = async() => await acFailRetry(failFn)('fake', 'params')
run()
.then(_=>console.log('res',_))
.catch(_=>console.log('err', _))
const ac = promise => promise.then(data => [null, data]).catch(err => [err])
const timeout = ms => new Promise(resolve => setTimeout(resolve, ms*1000))
const acFailRetry =async (asyncFn, ...params) => {
const retryBlock = async (retry=0, errs=[]) => {
if(retry > 3)
throw errs
const [err, resp] = await ac(asyncFn(...params))
if(err) {
await timeout(retry)
return await retryBlock(retry+1, errs.concat(err))
}
return resp
}
return await retryBlock()
}
let x = 0
const failFn = async (y,z) => {
if(x!==2)
throw `Error x:${++x}, ${y}, ${z}`
return `success! ${x} ${y} ${z}`
}
const run = async() => await acFailRetry(failFn, 'fake', 'params')
run()
.then(_=>console.log('res',_))
.catch(_=>console.log('err', _))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment