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

Add deferredPromise utility #43

Open
NullVoxPopuli opened this issue Oct 28, 2024 · 0 comments
Open

Add deferredPromise utility #43

NullVoxPopuli opened this issue Oct 28, 2024 · 0 comments

Comments

@NullVoxPopuli
Copy link
Contributor

Example code:

let reqWaiter = {
  resolve: null,
  promise: null,
  settled: async () => {
    await reqWaiter.promise;
    await settled();
  },
};

let id = 0;
function requestWaiter() {
  id++;
  let self = id;
  console.log('creating waiter', self);
  reqWaiter.resolve?.();
  reqWaiter.promise = new Promise((resolve) => {
    reqWaiter.resolve = () => {
      console.log('Resolving id', self);
      resolve();
      
      waitForPromise(
        new Promise((finish) => {
          requestAnimationFrame(() => {
	    console.log('clearing promise and resolve', self);
	    reqWaiter.promise = null;
	    reqWaiter.resolve = null;
	    finish();
          });
        }),
      );
    };
  });
}

And usage:

// in some async handler
reqWaiter.resolve?.();


// in your test actions
requestWaiter() // or reqWaiter.create();
// do actions which trigger async behavior
await reqWaiter.settled();

Why?

sometimes you need to wait outside of the waiter system
(maybe test-helpers use the settled state, and you need something to assure your mocked / passed callback holds up test execution before continuing)

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