Skip to content

Unable to timeout Promise. #31

Open
@wintertime-inc

Description

@wintertime-inc

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions