abort-controller icon indicating copy to clipboard operation
abort-controller copied to clipboard

Unable to timeout Promise.

Open wintertime-inc opened this issue 3 years ago • 0 comments

So I had an idea to use Abort Controller to stop long running async operations (basically for awaited promises put timeout). However it seems like it has no effect at all (same as pure NodeJS).

Idea behind this code is to abort long running awaited promises.

const AbortController = require('node-abort-controller');

async function init() {

  async function myLongRunningAsyncTask(timeToDone) {
    return new Promise(resolve => setTimeout(() => {
      console.log(`I got my long running task done in ${timeToDone}ms!`);
      resolve(true);
    }, timeToDone));
  }

  async function timeout(timeout, controller) {
    return new Promise( resolve => setTimeout( () => {
      console.log('Timeout signal');
      controller.abort();
      resolve('Timeout');
    }));
  }

  async function doSomethingAsync(promise, signal) {

    if (signal.aborted) {
      return Promise.reject('Timeout!');
    }

    return new Promise(  async (resolve, reject) => {
      signal.addEventListener('abort', () => {
        reject('Timeout!');
      });
      console.log('--- Promise Started ---');
      await promise;
      console.log('--- Promise Ended ---');
      resolve(promise);
    });
  }

  console.log('Start');
  const controller = new AbortController();
  const signal = controller.signal;
  try {
    await Promise.race([
      doSomethingAsync(
        myLongRunningAsyncTask(700), signal
      ),
      timeout(500, controller)
    ]);
  } catch (e) {
    console.log(e);
  }
  console.log('End');

}

init();

Sadly is has no effect....

Start
--- Promise Started ---
Timeout signal
Timeout!
End
I got my long running task done in 700ms!
--- Promise Ended ---

The perfection would be that long running async operation is killed when I call abort, however it seems like it is not possible?

wintertime-inc avatar Jun 15 '21 19:06 wintertime-inc