我在 TypeScript 中使用 async/await
执行一些基本的异步操作,但 TSLint 为下面的这两个函数抛出了神秘的错误消息。有没有人遇到过这些错误?在错误输出中没有提到管理规则,所以我不明白是什么原因造成的。任何想法将不胜感激。
主要要求:
import * as rp from 'request-promise'
export function getRequest(address: rp.Options): rp.RequestPromise {
return rp(address)
}
导出的异步函数:
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)
}
}
这得到:Promises must be handled appropriately
和 await of non-Promise
第 3 行。
使用这个导出的简单函数是:
client.on('message', message => {
if (message.content === 'green') {
getStatus(message)
}
})
这也得到 Promises must be handled appropriately
。
附加信息:
即使错误消息没有提及,这似乎是 Promises must be handled appropriately
的管理规则:
https://palantir.github.io/tslint/rules/no-floating-promises/
并且这个 Issue 提到了 await of non-Promise
:
https://github.com/palantir/tslint/issues/2661
最佳答案
那是一条蹩脚的错误信息。一个更好的可能是,
Promise
类型的每个表达式都必须以对 .catch
的调用或对 .then
的调用结束,并带有拒绝处理程序(source)。
所以,例如,如果你这样做
PromiseFunction()
.catch(err => handle(err))
.then(() => console.log('this will succeed'))
那么你仍然会遇到 tslint 问题,因为 .then(...)
的类型是一个 promise,它必须以 catch 结束。修复方法是附加一个 .catch
子句,例如,
PromiseFunction()
.catch(err => handle(err))
.then(() => console.log('this will succeed'))
.catch(() => 'obligatory catch')
或者通过以下方式为该行禁用 tslint:
PromiseFunction()
.catch(err => handle(err))
// tslint:disable-next-line:no-unsafe-any
.then(() => console.log('this will succeed'))
或者,您可以颠倒 .then
和 .catch
语句的顺序。但是,如果确实发生错误,这会阻止 .then
执行,如果您遇到此问题,您可能希望这样做。
关于javascript - 这可能是关于什么的? [TsLint 错误 : "Promises must be handled appropriately"],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43980188/