Created
February 18, 2019 11:35
-
-
Save mstaicu/84b251e0987b714ac12f92d1445d96d6 to your computer and use it in GitHub Desktop.
Promise composition for async control flow
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
function retry(fn) { | |
return function(data) { | |
return new Promise((resolve, reject) => { | |
var retries = 10, | |
error; | |
function attempt() { | |
if (retries === 0) { | |
reject(error); | |
} | |
fn(data) | |
.then(resolve) | |
.catch(err => { | |
error = err; | |
retries = retries - 1; | |
return setTimeout(attempt, 200); | |
}); | |
} | |
attempt(); | |
}); | |
}; | |
} | |
function getData(data) { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => resolve(data), 300); | |
}); | |
} | |
function postData(data) { | |
return Promise.resolve(data); | |
} | |
function deleteData(data) { | |
return Promise.resolve(data); | |
} | |
var composePromises = (...functions) => initialData => | |
functions.reduceRight((acc, fn) => Promise.resolve(acc).then(fn), initialData); | |
var fireRequests = composePromises( | |
data => { | |
console.log(data); | |
return Promise.resolve(data); | |
}, | |
retry(deleteData), | |
retry(postData), | |
retry(getData) | |
); | |
fireRequests('Liftoff'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment