SebastienGllmt / eslint-plugin-no-floating-promise

Detects missing await on async function calls
17 stars 3 forks source link

How to flag assignment of Promise to variable without await #7

Open vicatcu opened 3 years ago

vicatcu commented 3 years ago

The following is an extraordinarily common pattern that this plugin seems to not register as a warning / error, but almost always is:

function WaitForIt() {
  return new Promise(r, j) {
    setTimeout(r, 1000);
  }
}

async function WaitThenDo() {
   const x = WaitForIt();   // this is a problem because it doesn't await
   console.log('Doing it!');
}

The mere fact that the WaitForIt() call is bound to an assignment seems to prevent the plugin from noticing this as a problem? Is this a "bug" in this plugin, or is there a better / different plugin to handle this very common case?

SebastienGllmt commented 3 years ago

Probably the root error here is better caught by a linting rule for unused variable. There isn't really any way for the plugin to know whether or not the variable you assign to will actually be used anywhere (it's equivalent to the halting problem)

RobertSandiford commented 3 years ago

@vicatcu That's not the purpose of this plugin. I too am looking for that. Did you find one?

@SebastienGllmt The issue is not related to unused variable. Normally the variable x would be used (otherwise don't assign it).

The problem is that the writer wants x to be the result of the promise, not the promise, e.g.

   return WaitForIt();

Is often a mistake, where the writer meant to do

    return await WairForIt();

(Although different to this plugin,) a rule that shows a warning when a function returning a promise (or just a function declared as async) is called without await, would be very helpful.

Do you know how to do this I wonder?

Of course there are times where we want to call an async func and not await - either taking asynchronous action when the promise completes with .then(), or just not having any follow on action, but there are many projects where this is rare/unused, and a warning to catch common mistakes would be very good there.