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

promiseStateAsync swallows unhandled rejections if they are rejected after being observed by the Promise.race #12

Open
CloudNStoyan opened this issue Mar 15, 2024 · 3 comments
Labels
bug Something isn't working help wanted Extra attention is needed

Comments

@CloudNStoyan
Copy link

Using the following snippet, promiseStateAsync will swallow unhandled rejections if the promise is rejected after being inspected by promiseStateAsync

const marker = Symbol("marker");

async function promiseStateAsync(promise) {
  if (!(typeof promise === "object" && typeof promise.then === "function")) {
    throw new TypeError(`Expected a promise, got ${typeof promise}`);
  }

  // Ensure unhandled rejections don't get swallowed.
  await new Promise((resolve) => {
    if (typeof setImmediate === "function") {
      setImmediate(resolve);
    } else {
      setTimeout(resolve);
    }
  });

  try {
    return (await Promise.race([promise, marker])) === marker
      ? "pending"
      : "fulfilled";
  } catch {
    return "rejected";
  }
}

let reject;
let promise = new Promise((_res, rej) => {
  reject = rej;
});

const promiseState = await promiseStateAsync(promise);
console.log(promiseState);

setTimeout(() => {
  reject("dinosaur");
  console.log("the setTimeout triggered");
}, 1000);

Note: in the browser I used the following events to check if the unhandled rejection event is raised, which it wasn't:

window.addEventListener("unhandledrejection", (ev) => {
  console.warn(`UNHANDLED PROMISE REJECTION: ${ev.reason}`);
});

window.addEventListener('error', (ev) => {
  console.warn(`UNHANDLED ERROR: ${ev.reason}`);
});

This behavior is seen in both Node and browsers

I have tested it on the following platforms:
Win11 Chrome Version 122.0.6261.129
Win11 Firefox Version 123.0.1
macOS Sonoma 14.4 Chrome Version 122.0.6261.129
macOS Sonoma 14.4 Firefox Version 123.0.1
macOS Sonoma 14.4 Safari Version 17.4 (19618.1.15.11.12)
Node versions v18.16.1 and v20.11.0 on both Win11 and macOS Sonoma 14.4

sindresorhus added a commit that referenced this issue Mar 16, 2024
@sindresorhus
Copy link
Owner

Thanks for reporting. I'm not sure how to fix this, but I have at least added a failing test: 4634d7b

@sindresorhus sindresorhus added bug Something isn't working help wanted Extra attention is needed labels Mar 16, 2024
@CloudNStoyan
Copy link
Author

Hello again, I have a solution for this Issue:

export async function promiseStateAsync(promise) {
	if (!(typeof promise === 'object' && typeof promise.then === 'function')) {
		throw new TypeError(`Expected a promise, got ${typeof promise}`);
	}

	let promiseState = 'pending';
	let promiseSettled = false;

	// `.finally` doesn't handle uncaught rejections
	promise.finally(() => {
		promiseSettled = true;
	});

	// We wait an event loop for `.finally` to resolve.
	// If it doesn't resolve by then that means the promise
	// is still `pending`.
	await new Promise(resolve => {
		if (typeof setImmediate === 'function') {
			setImmediate(resolve);
		} else {
			setTimeout(resolve);
		}
	});

	// If the passed function to `.finally` is not
	// invoked in an event loop that means the promise
	// is not yet settled, so we return `pending`.
	if (!promiseSettled) {
		return promiseState;
	}

	promise.then(
		() => {
			promiseState = 'fulfilled';
		},
		() => {
			promiseState = 'rejected';
		},
	);

	// We wait for 1 event loop for `.then` to resolve
	// knowing that the promise is settled to extract
	// the status of the promise
	await new Promise(resolve => {
		if (typeof setImmediate === 'function') {
			setImmediate(resolve);
		} else {
			setTimeout(resolve);
		}
	});

	return promiseState;
}

I ran the repo tests successfully on:
macOS Sonoma 14.4.1 (23E224)
Node:

  • v18.16.1
  • v20.11.0

Win 11
Node:

  • v18.19.0
  • v20.11.0

Results:
6 tests passed
4 unhandled rejections

I also ran the following assertions in the browsers:

(async () => {
  console.assert(await promiseStateAsync(Promise.resolve()) === "fulfilled");
  console.assert(await promiseStateAsync(Promise.reject("Dino 1")) === "rejected");
  console.assert(await promiseStateAsync(new Promise(() => {})) === "pending");
  
  const {promise: promiseThatWillReject, reject } = Promise.withResolvers();
  
  console.assert(await promiseStateAsync(promiseThatWillReject) === "pending");
  
  setTimeout(async () => {
    reject("Dino 2");
    console.assert(await promiseStateAsync(promiseThatWillReject) === "rejected");
  }, 150);
  
  const {promise: promiseThatWillResolve, resolve} = Promise.withResolvers();
  
  console.assert(await promiseStateAsync(promiseThatWillResolve) === "pending");
  
  setTimeout(async () => {
    resolve();
    console.assert(await promiseStateAsync(promiseThatWillResolve) === "fulfilled");
  }, 150);
})();

Tested on the following browsers:
macOS Sonoma 14.4.1 (23E224)

  • Safari Version 17.4.1 (19618.1.15.11.14)
  • Chrome Version 124.0.6367.119
  • Firefox Version 125.0.3

Win 11

  • Chrome Version 124.0.6367.119
  • Firefox Version 125.0.3

Results:
Uncaught (in promise) Dino 1
Uncaught (in promise) Dino 2 (x2)

The downside is that the state will take an extra event loop run to be returned (if the promise is not pending)

Also this solution doesn't need to pass 1 to the setTimeout because .finally doesn't handle uncaught rejections like Promise.race.

The stackoverflow answers that led me to .finally:
https://stackoverflow.com/a/41130732
https://stackoverflow.com/a/63534721

@CloudNStoyan
Copy link
Author

It turns out my solution is flawed because .finally always throws an unhandled rejection when its parent promise rejects (it doesn't matter if the parent promise has .catch handle), unless you put a .catch on the returned promise from .finally which will handle the rejection and have the same problem as Promise.race.

TL;DR: My solution throws an unhandled rejection even when the promise was handled.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

2 participants