typescript - 当返回 promise 的函数必须是异步的时,JS 错误有助于防止 typescript 错误 @typescript-eslint/promise-function-async
问题描述
我觉得这没有必要。难道这个错误规则是为了防止promise that return,no error?这个错误有什么帮助?
但我不明白这里的真正含义是什么:
非异步 Promise - 返回函数在技术上都可以。处理这些函数结果的代码通常需要处理这两种情况,这可能会变得复杂
指的是both
解决还是拒绝或其他什么?
解决方案
解释规则文档中的描述:如果一个函数既可以抛出同步错误又可以返回被拒绝的承诺,那么编写代码来处理它是很困难的。这个规则确保一个函数要么做一个,要么做另一个,从不两者兼而有之。
例如,如果一个函数可能同时存在同步错误和异步错误,那么处理它们需要像这样:
function example (obj) {
// this might throw synchronously
const result = JSON.stringify(obj);
// This might reject (asynchronously)
return new Promise((resolve, reject) => {
if (Math.random() > 0.5) {
resolve(result);
} else {
reject('too bad');
}
});
}
try {
example({ foo: 'bar' })
.catch(err => {
// Have to split my error handling to two places, not one
});
} catch (err) {
// Have to split my error handling to two places, not one
}
而不是一个捕获
example({ foo: 'bar' })
.catch(err => {
// All error handling in one place
});
与所有 lint 规则一样,如果您觉得它没有用,请随意禁用它。
推荐阅读
- mysql - 在 Superset 时间列中使用整数年份
- mysql - 带有简单游标的简单存储过程不会编译
- python-3.x - 如何循环python游戏但也让它更干净?
- docker - 错误:不允许附加属性 db-migrator
- node.js - 为什么在 Sequelize 中创建关联模型时使用大写键?
- java - 如何使用 nanoTime 准确预测时间?
- swift - Mapkit 获取地标的当前坐标
- google-maps - 如何在颤动中更改谷歌地图 API 的“我的位置”按钮位置?
- strimzi - "在版本 "kafka.strimzi.io/v1alpha1" 中没有匹配类型 "Kafka""
- node.js - 如何在Nodejs中转换数组中的缓冲区?