Created
May 11, 2017 04:45
-
-
Save aidanhmiles/fdd3ca54ecf54fc0b8f99213d3922acb to your computer and use it in GitHub Desktop.
One way to retry promises
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
const lodash = require('lodash'); | |
function main () { | |
// Arbitrary async operation. Sums two coin-flips (random 0 or 1). Only resolves when the sum is 0. | |
function asyncOperation() { | |
return new Promise((resolve, reject) => { | |
let sum = lodash(new Array(2)) | |
.fill(null) | |
.map(() => Math.round(Math.random())) | |
.reduce((accum, next) => accum + next, 0); | |
console.log('Sum of the array is: ' + sum); | |
if (sum === 0) { | |
resolve(); | |
} | |
else { | |
reject('Not an error'); | |
} | |
}); | |
} | |
function retryOperation(resolve,reject) { | |
return asyncOperation() | |
.then(() => { | |
console.log('Operation succeeded'); | |
resolve('Success'); | |
}) | |
.catch(reason => { | |
console.log('Operation failed; retrying'); | |
if (reason === 'Not an error') { | |
return retryOperation(resolve, reject); | |
} | |
else { | |
reject(reason); | |
} | |
}) | |
} | |
return new Promise((resolve, reject) => { | |
return retryOperation(resolve, reject); | |
}) | |
.then(() => { | |
console.log('Success'); | |
}) | |
.catch(error => { | |
console.log(error); | |
}); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment