function sleep(t) {
return new Promise((resolve, reject) =>{
setTimeout(() => {
console.log('timeout!')
return resolve({isTimeout: true})
}, t);
});
}
function thirdPartyFunction(t) { // thirdPartyFunction can't be edited
return new Promise((resolve, reject) =>{
setTimeout(() => {
console.log('thirdPartyFunction completed!')
return resolve({success: true})
}, t);
});
}
function main() {
return new Promise(async(resolve, reject) => {
try {
let thirdPartyFunctionExecutionTime = Math.floor(Math.random() * 10) + 1;
thirdPartyFunction(thirdPartyFunctionExecutionTime * 1000, false).then( (r) => {
console.log('should not execute this if thirdPartyFunctionExecutionTime > timeout') // only goal
// other code which is not useful after timeout
});
const timeout = 3;
console.log(`thirdPartyFunctionExecutionTime: ${thirdPartyFunctionExecutionTime}, timeout - ${timeout}`)
await sleep(timeout * 1000, true);
throw 'stop main()'
// return
} catch (error) {
console.log('in catch')
return;
}
})
}
main()
Timeout is fixed. thirdPartyFunctionExecutionTime might be very large (sometimes) in my actual case, say 30 secs. I don't want something to be running on background after timeout.
thirdPartyFunction promise function should stop execution on timeout.