What could this be about? [TsLint Error: "Promises must be handled appropriately"]

cinnaroll45 picture cinnaroll45 · May 15, 2017 · Viewed 40.7k times · Source

I'm doing some basic asynchronous operations using async/await in TypeScript but TSLint is throwing mysterious error messages for these two functions below. Has anyone encountered these errors before? On the error output the governing rule is not mentioned, so I don't understand what's causing these. Any ideas would be greatly appreciated.

The main request:

import * as rp from 'request-promise'

export function getRequest(address: rp.Options): rp.RequestPromise {
  return rp(address)
}

Exported async function:

export async function getStatus(message: Message) {
  try {
    const res = await getRequest(address)
    if (res.ready) {
      message.reply('...')
    } else {
      message.reply('...')
    }
  } catch (err) {
    message.reply(err)
  }
}

This gets: Promises must be handled appropriatelyand await of non-Promise for line #3.

The simple function that uses this export is:

client.on('message', message => {
  if (message.content === 'green') {
    getStatus(message)
  }
})

This also gets Promises must be handled appropriately.

Additional information:

Even though the error message doesn't mention it, this seems to be the governing rule for Promises must be handled appropriately: https://palantir.github.io/tslint/rules/no-floating-promises/

And this Issue mentions await of non-Promise: https://github.com/palantir/tslint/issues/2661

Answer

Warlike Chimpanzee picture Warlike Chimpanzee · Feb 4, 2018

That's a crappy error message. A better one might be,

every expression of type Promise must end with a call to .catch or a call to .then with a rejection handler (source).

So, for example, if you do

PromiseFunction()
  .catch(err => handle(err))
  .then(() => console.log('this will succeed'))

then you will still have a tslint problem, because the type of .then(...) is a promise, and it has to end with a catch. The fix would be appending a .catch clause, for example,

PromiseFunction()
  .catch(err => handle(err))
  .then(() => console.log('this will succeed'))
  .catch(() => 'obligatory catch')

or just disabling tslint for that line via:

PromiseFunction()
  .catch(err => handle(err))
  // tslint:disable-next-line:no-unsafe-any
  .then(() => console.log('this will succeed'))

Alternatively, you could reverse the order of the .then and .catch statements. However, that stops the .then from executing if an error does occur, which you presumably want if you encountered this problem.