Skip to content

Instantly share code, notes, and snippets.

@Oluwasetemi
Created April 7, 2024 17:16
Show Gist options
  • Save Oluwasetemi/a539b189b4d19c9dd770f5dbb3cf2285 to your computer and use it in GitHub Desktop.
Save Oluwasetemi/a539b189b4d19c9dd770f5dbb3cf2285 to your computer and use it in GitHub Desktop.
// getData () => Promise<Data>
// postData (data: Data) => Promise<vo id>
/**
* 1. Every 10 seconds, request data via getData and pass the response to postData
* 2. If getData rejects, it should retry until it resolves successfully
* 3. If postData rejects, it should re-run, being passed the same data object, until it resolves successfully
* 4. Retries should happen immediately, it should not wait 10 seconds to retry
*
*
* @param {() => Promise<Data>} getData
* @param {(data: Data) => Promise<void>} postData
*
*/
function requestDataAndPostData(getData, postData) {
getData()
.then((data) => {
postData(data).catch(() => {
requestDataAndPostData(getData, postData);
});
})
.catch(() => {
requestDataAndPostData(getData, postData);
});
}
function execute() {
requestDataAndPostData(getData, postData);
setTimeout(execute, 10000);
}
const getData = () => {
let data = { data: 'data' };
console.log(data);
return Promise.resolve(data);
};
const postData = (data) => {
if (Math.random() > 0.5) {
console.log('data posted rejected');
return Promise.reject();
}
console.log('data posted');
return Promise.resolve();
};
// todo: uncomment to run
// execute(getData, postData);
// ======= async/await version =========
async function requestDataAndPostData() {
try {
const data = await getData();
await postData(data);
} catch (error) {
console.error('Error:', error);
// Retry logic for getData
await requestDataAndPostData();
}
}
async function execute() {
while (true) {
try {
await requestDataAndPostData();
await new Promise((resolve) => setTimeout(resolve, 10000)); // Wait for 10 seconds
} catch (error) {
console.error('Error:', error);
}
}
}
// await execute(getData, postData);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment