Floating promise check in Typescript Eslint (no floating Promises)

Asked

Viewed 266 times

1

I have the following method:

async sync({model, event, data}: {model: string, event: string, data: Category}) {
  if (model === 'category') {
    switch (event) {
      case 'created':
        await this.categoryRepo.create({
          ...data,
          createdAt: new Date(),
          updatedAt: new Date()
        });
        break;
    }
  }
}

But when I make his call:

this.sync({model, event, data});

Typescript returns me the following error in this:

Eslint: Promises must be handled appropriately or explicitly marked as Ignored with the void Operator. (@typescript-Eslint/no-floating-Promises)

How can I treat that?

1 answer

1


Remember that all asynchronous function in Javascript returns (always) a Promise. Thus, it is ideal that you treat it properly (since it will be solved at another time of execution of the code), either with then or catch.

The error, in accordance with the documentation of the rule in question, is because:

Untreated promises can cause a number of problems, such as improper sequence of operations, ignored rejections, etc.

The same documentation also indicates that correct the error the method can be used Promise.prototype.catch or the second argument of Promise.prototype.then (the effect of which is similar to that of catch).

So in your case, you need to do something like:

this.sync({ model, event, data }).catch((error) => {
  // Lide com o erro...
});

Or else:

this.sync({ model, event, data }).then(
  () => {
    // Tudo correu bem (1º argumento do then).
  },
  (error) => {
    // Lide com o erro (2º argumento do then).
  }
);

It is more a guarantee to prevent future mistakes. It is an example of "good practice". Of course it is good to do, but it is also good to understand why it’s good to do it.

Related in Environment Node.js is the UnhandledPromiseRejectionWarning (notice of rejection of untreated promise).


Just one final remark: not a Typescript error per se, but a Eslint plugin Typescript. You can identify the source of the error at the end of the error message:

Eslint: Promises must be handled appropriately or explicitly marked as Ignored with the void Operator. (@typescript-Eslint/no-floating-Promises)

Note at the end that the error message comes from the rule no-floating-promises of plugin @typescript-eslint eslint.

A Typescript error would be something like:

Parameter 'x' implicitly has an 'any' type. ts(7006)

Note that this hypothetical error is in fact Typescript. More specifically, the code error (internal Typescript) 7006.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.