Skip to content
Advertisement

JavaScript Promises – force promise to resolve

Considering that I have the following:

JavaScript

The infinite_task is a promise that never resolves or rejects. I tried to use Promise.race but it will never compare both promises, since infinite_task never ends.

How can I force infinite_task to resolve after a timeout (in this case, after 5 seconds)?

Advertisement

Answer

You have a behavioural error in the setTimeout function. You are passing the result of the resolve function (that is undefined) as parameter of the setTimeout, when you should pass a callback. This means that your timeoutPromise actually resolves instantly and not after the real timeout. This behaves as you expect:

JavaScript

Decomposing your code:

For clarity I decompose in steps what you did:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement