Ceelearn anddo
Ceelearn anddo

Reputation: 79

How to return a rejected promise when it takes the function too long to return a response by itself in Node?

I made a back-end in Node.js.

The back-end contains a function named algorithm.make(). This function has a promise as return type. Sometimes the application needs three seconds to fully execute the algoritm.make function and sometimes it needs ten minutes.

I would like to always return a response (a resolved or rejected promise) after a specific amount of seconds.

I tried:

....

try {
       return await Promise.race([
           this.wait(4000),
           algorithm.make()
       ]);
} catch(err) {
        console.log(err);
}

Wait function:

static wait(ms) {
    return new Promise((_, reject) => {
        setTimeout(() => reject(new Error('timeout succeeded ' + ms)), ms);
    });
}

With this code the algorithm.make() will just fully execute (and it will not be stopped after 4000ms).

But when I do this, it will return a rejected promise after 2 seconds:

try {
       return await Promise.race([
           this.wait(4000),
           this.wait(2000),
       ]);
} catch(err) {
        console.log(err);
}

I don't know why it is working with two setTimeouts but not with one setTimeout and one real function.

Upvotes: 0

Views: 672

Answers (1)

Ceelearn anddo
Ceelearn anddo

Reputation: 79

I tried another approach and that was working.

In the Node.js function I calculated the date/time when it will took too long to respond.

this.returnTime = new Date();
this.returnTime.setSeconds( this.returnTime.getSeconds() + this.timer );

And then I added an extra check in a function that is looped several times:

if(this.returnTime > new Date()) {
 .....

So if the current date/time is newer than the this.returnTime, then it will return something. Otherwise it will keep going

Upvotes: 1

Related Questions