0

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 returning 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 .

Camto
  • 23
  • 1
  • 9
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) - I hope it answers your question. – Omri Luzon May 14 '18 at 18:08
  • 1
    When you say it "runs forever", do you mean the page freezes? If yes, you cannot have a "max execution time" and need to rework your function to make it error prone. – Karl-André Gagnon May 14 '18 at 18:09
  • "*stops running the function*" - how can it do that? – Bergi May 14 '18 at 18:10
  • I `calc` actually asynchronous? If yes, it should take a callback or better return a promise, if no, then you cannot give it a time limit with `setTimeout` and your promise code won't work like that. – Bergi May 14 '18 at 18:11
  • 2
    "*How can I return the result from the line with return?*" - you can't, it's asynchronous. Just return the `timed` promise! To access the value, you have to use `then` as it's supposed to. – Bergi May 14 '18 at 18:14
  • I used the implementation here https://stackoverflow.com/questions/32461271/nodejs-timeout-a-promise-if-failed-to-complete-in-time and if `calc()` contained a `while(1) {}` it `reject`ed with "Time limit reached" as I want, is there a way to return that, or the `result`? – Camto May 14 '18 at 18:17
  • 1
    @BenjaminPhilippe I doubt it works if your code contains `while (1)`. Can you please post your complete implementation? – Bergi May 14 '18 at 18:22
  • @Bergi What worked was using `if((new Date).getTime() - start_time)` every time the loop went around, thanks for your time! – Camto May 14 '18 at 22:33

0 Answers0