Last active
September 14, 2022 10:27
-
-
Save swalahamani/6fe9ab6b27df0ba300ba0a71f3588e95 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* The implementation of this is heavily inspired from the article: | |
* https://ourcodeworld.com/articles/read/1544/how-to-implement-a-timeout-for-javascript-promises | |
*/ | |
/** | |
* Waits the execution till passed milliseconds. | |
* | |
* @param {*} milliseconds | |
* @returns | |
*/ | |
const waitTill = (milliseconds) => { | |
return new Promise((resolve) => { | |
setTimeout(resolve, milliseconds); | |
}); | |
}; | |
/** | |
* Sample function to demonstrate a long process. | |
* | |
* @returns | |
*/ | |
async function myLongProcess () { | |
await waitTill(10000); | |
console.log("myLongProcess execution completed"); | |
return "Result from myLongProcess"; | |
} | |
/** | |
* Accepts a promise and a timeout in milliseconds. | |
* If the promise is not get resolved/rejected in the specified | |
* timeout, it returns a rejected promise "timeout". | |
* | |
* @param {*} promise | |
* @param {*} timeoutInMilliseconds | |
* @returns | |
*/ | |
function promiseTimeout (promise, timeoutInMilliseconds){ | |
return Promise.race([ | |
promise, | |
new Promise(function(resolve, reject){ | |
setTimeout(function() { | |
reject("timeout"); | |
}, timeoutInMilliseconds); | |
}) | |
]); | |
} | |
/** | |
* Test ground | |
*/ | |
async function main() { | |
console.log("Program started....") | |
/** | |
* Please note that, we need to take the promise of the long running | |
* function for passing it to the promiseTimeout. So, don't make an | |
* await call here for preserving the Promise. | |
*/ | |
const myLongProcessPromise = myLongProcess(); | |
try { | |
const TIMEOUT = 5000; | |
/** | |
* Try changing the value of TIMEOUT to something different to see | |
* the difference. Our long running function need 10000 ms to finish | |
* it's execution. Thus, any timeout value less than that will result | |
* in killing the execution and hitting the timeout. | |
*/ | |
const result = await promiseTimeout(myLongProcessPromise, TIMEOUT); | |
console.log("Result :>> ", result); | |
} catch (error) { | |
/** | |
* If the error is thrown from the timeout Promise, it can be equated | |
* to "timeout". Else it will be some different error and can be handled | |
* in the else block appropriately. | |
*/ | |
if (error === "timeout") { | |
console.log("Error :>> timeout error :>> ", error); | |
} else { | |
console.log("Error :>>", error); | |
} | |
} | |
console.log("Program finished") | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment