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

Stop promise not entirely compatible with Promise.race #74

Open
jessmorecroft opened this issue Jun 27, 2022 · 0 comments
Open

Stop promise not entirely compatible with Promise.race #74

jessmorecroft opened this issue Jun 27, 2022 · 0 comments
Assignees

Comments

@jessmorecroft
Copy link

Hi, noticing in my tests that when i'm trying to use the stop promise in a call to Promise.race, it's not prioritising this promise even though it's clearly settled. I'm guessing this is happening because Stop is not a "native" promise, and Promise.race is not seeing it as immediately settled?

To demonstrate, here's some code that runs to completion:

    async function* increment() {
      let count = 0;
      for (;;) {
        ++count;
        await promisify(nextTick)(); // this line is required or we never exit
        yield count;
      }
    }

    const repeater = new Repeater<number>(async (push, stop) => {
      const iter = increment()[Symbol.asyncIterator]();
      //const stop2 = stop.then((a) => a); // workaround
      for (;;) {
        const result = await Promise.race([stop, iter.next()]); // workaround: use stop2 here instead of stop
        if (result === undefined) {
          // stopped by our caller
          await iter.return();
          break;
        }
        if (result.done) {
          // source iterator is done
          stop();
          break;
        }

        await push(result.value);
      }
    });

    for await (const count of repeater) {
      if (count >= 5) {
        break;
      }
    }

If you now try running this but this time comment out the "nextTick" line, you'll note the code hangs. What's actually happening is the implicit call to end the repeater on the final loop's break never ends, as the code is stuck in the repeater loop with the call to Promise.race always returning the promise result for iter.next, despite stop having clearly resolved and being listed first.

To "fix" this behaviour I can uncomment the workaround line and use stop2 in the race call. This then causes race to resolve to the stop2 promise and we therefore exit the loop.

Please let me know if there's a better way to structure this code (dealing with never ending source async iterators) to avoid this entirely.

@brainkim brainkim self-assigned this Jul 10, 2022
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

2 participants