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 appropriately
and 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
A "floating" Promise is one that is created without any code set up to handle any errors it might throw.
async and await Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With