Thursday 18 May 2017

How to reject a resolving promise on timeout?

I have a promise that needs to be rejected due to the resolve taking too long. In my code I am attempting to use a timeout to reject the promise. I have followed the example of Promise timeout tutorial but can't get the promise to reject after the timeout.

/* I added setTimeout 10 seconds to the package to give it a delay */
const package = require('package');

const promiseTimeout = function(ms, promise){
  // Create a promise that rejects in <ms> milliseconds
  let timeout = new Promise((resolve, reject) => {
    let id = setTimeout(() => {
    clearTimeout(id);
    console.log("timeout finished at " + ms + "ms but promise won't reject");
    reject('Timed out in '+ ms + 'ms. - Reject Message')
    }, ms)
  })

  // Returns a race between our timeout and the passed in promise
  return Promise.race([
    promise,
    timeout
  ])
}

const prolongedPromise = function(){
    return new Promise((resolve, reject) => {
        package.asyncFunction(function(data) {
          resolve(data) /* Takes 10 seconds to resolve */
        })
    })
};

/* Attempting to race promises to get reject to execute on timeout */
let promiseRace = promiseTimeout(2000, prolongedPromise());
promiseRace.then(response => {
    resolve(response); /* Always resolves even after timeout is executed */
}, error => {
    reject(error);
}).catch(error => {
    reject(error);
})

I'm not sure but it may be possible that the promise is already being resolving (with the 10 second timeout) which will not allow the reject to execute.

It's hard to showcase the full environment as I have to follow the package's API to get data. I have a tester environment in github that has prepared a 10 second wait on the asyc function I'm trying to resolve if anyone is curious on seeing the problem fully.

How can I get my promise to reject with a timeout?



via Jonathan002

No comments:

Post a Comment