I wrote a function calc
that can finish normally or run forever based on user input and I can't control that. I want to write a function limited_calc
that wraps around it to provide a time limit and stops running the function once the time is up. I've got the time limit working with something like this:
function limited_calc(max_time, input) {
var timed = new Promise((resolve, reject) => {
setTimeout(reject, max_time, "Time limit reached");
resolve(calc(input));
}
return ???
}
function calc(input) {
// (do the stuff)
}
Using .then()
with console.log()
shows the correct output, but return
ing in .then()
gives a promise as it's supposed to, but not the value itself. How can I return the result from the line with return ???
? I know setting an outer variable and then another, longer timeout works, but seems unsafe. How do I do this the intended way?
Resource I used: the class defined in the accepted answer NodeJS Timeout a Promise if failed to complete in time .