Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to timeout Promise. #31

Open
wintertime-inc opened this issue Jun 15, 2021 · 0 comments
Open

Unable to timeout Promise. #31

wintertime-inc opened this issue Jun 15, 2021 · 0 comments

Comments

@wintertime-inc
Copy link

wintertime-inc commented Jun 15, 2021

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant