I'm using a 3rd party library to do a heavy calculation. The problem is it hangs for some input. I'd like to add timeout to the synchronous operation. My code runs in single threaded node environment on GCP (Cloud Fuctions).
const result calculate(x, y);
This is what I've already tried:
let calculation = new Promise((resolve, reject) => {
const result = calculate(x, y)
resolve(result)
})
let timeout = new Promise((resolve, reject) => {
let id = setTimeout(() => {
clearTimeout(id);
reject()
}, 5000)
})
const result = await Promise.race([timeout, calculation])
Unfortunately it doesn't work, as the calculate
method locks the thread so the timeout can't reject the promise. Is it possible to make synchronous method timeout after a given time?