Search code examples
javascriptnode.jses6-promise

How to handle a Promise that is never resolve or rejected without using timeout


I am using TypeScript in Node.js. I have simplified my code to the following:

async function runPromise(promise: Promise<unknown>) {
    await promise
    console.log('done')
}

void runPromise(new Promise(() => {
    console.log('in promise')
}))

When I run this, I get the following output and then the process ends with a 0 exit status:

in promise

Because the Promise is never resolved or rejected, it never runs the console.log('done') line.

I would like to be able to handle cases where runPromise is called with a Promise that never resolves. Is there a way to have this throw an error rather than silently exit? I would like to avoid using some kind of timeout as I won't really know how long it should take.


I should have asked this originally, but why does Node.js shut down the process when there is an outstanding promise rather than hanging indefinitely? I see reference to the halting problem. I assumed Node.js would be aware of outstanding promises, but I see that must not be a valid assumption.

Also, I have corrected the code so the promise does resolve but it took quite a bit of time to debug, so I was just trying to improve my runPromise function to be more strict and fail with an error rather than silently shutting down. I would like to prevent such errors in the future.


Solution

  • As discussed in the comments: This is impossible.

    There is no general algorithm to determine whether a Promise will settle or not, for the same reason there is no general algorithm to determine whether a program will halt or not.

    That said, either just use a timeout or fix the source of that Promise.