Created
February 12, 2019 19:32
-
-
Save michaelwclark/ef5d4c58a648eae70819149526863bd4 to your computer and use it in GitHub Desktop.
Allows for keepalive to be called every X ms while waiting for task to complete
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
//reqs: | |
// if task takes longer the X ms to complete then send a resposne to caller and continue to process task | |
const delay = (ms = 500) => | |
new Promise(resolve => setTimeout(resolve, ms)) | |
const taskA = async () => { | |
await delay(1200) | |
console.log('task A complete') | |
return 'A' | |
} | |
const keepAliveFn = async () => { | |
console.log('keep alive') | |
return 'B' | |
} | |
const keepAliveProcessor = async (taskFn, keepAliveCb, timeout) => { | |
const keepAliveWrapper = async () => { | |
const result = await keepAliveCb() | |
return { __timeout: true, result } | |
} | |
const taskFnWrapper = async () => { | |
const result = await taskFn() | |
return { __timeout: false, result } | |
} | |
let processingComplete = false | |
const taskPromise = taskFnWrapper() | |
let race | |
while (!processingComplete) { | |
race = await Promise.race([taskPromise, keepAliveWrapper()]) | |
processingComplete = race.__timeout === false | |
if (!processingComplete) { | |
await delay(timeout - 100) | |
} | |
} | |
return race.result | |
} | |
keepAliveProcessor(taskA, keepAliveFn, 300) | |
.then(x => console.log('fin', x)) | |
.catch(x => console.error(x)) | |
//OUTPUT: | |
// keep alive | |
// keep alive | |
// keep alive | |
// keep alive | |
// keep alive | |
// keep alive | |
// task A complete | |
// keep alive --- maybe an issue, haven't solved cancelling last keep alive | |
// fin A |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment