eslint-plugin-unicorn icon indicating copy to clipboard operation
eslint-plugin-unicorn copied to clipboard

`prefer-top-level-await`: Do not report cases where the promise is assigned to a variable

Open jhnns opened this issue 11 months ago • 3 comments

Description

Hello 👋, thank you for this great plugin :)

I have a case where I create a Promise on the top-level and assign it to a variable. Later, in an asynchronous function, I await the promise:

const preparationDone = prepareSomething();

export async function doSomethingThatNeedsPerparation() {
	await preparationDone;
	// ...
}

The motivation behind this is as follows: I don't want to use top-level await because I don't want to slow down the evaluation of the module scope. The result of the Promise must only be available at the time when the asynchronous function is executed.

Would it therefore be possible not to report cases in which the Promise is assigned to a variable?

Fail

run().catch(error => {
	console.error(error);
	process.exit(1);
});

Pass

const resultOfRun = run();

Additional Info

I know that the rule might be "too relaxed" in that case, but I still think that my use case is valid and should not reported as an anti-pattern :)

jhnns avatar Dec 24 '24 12:12 jhnns

I agree that this is a useful pattern and should not be reported on.

sindresorhus avatar Dec 24 '24 13:12 sindresorhus

Would you accept a PR for it? :)

jhnns avatar Dec 24 '24 14:12 jhnns

Yes

sindresorhus avatar Jan 24 '25 09:01 sindresorhus