Skip to content

Instantly share code, notes, and snippets.

@aidanhmiles
Created May 11, 2017 04:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aidanhmiles/fdd3ca54ecf54fc0b8f99213d3922acb to your computer and use it in GitHub Desktop.
Save aidanhmiles/fdd3ca54ecf54fc0b8f99213d3922acb to your computer and use it in GitHub Desktop.
One way to retry promises
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