typescript - 处理响应类型 async/await - IDE 错误
问题描述
我被这样的场景难住了:我利用一个 promise(then|catch) 来处理错误,但也等待代码的清洁。以下是我正在查看的内容:
let rules:Rules = await elb.describeRules(params).promise().then(_handleSuccess).catch(_handleError);
错误处理程序是:
function _handleError(e:AWSError) {
console.error(`Error getting rules info - [${e.code}] ${e.message}`);
throw(e)
}
成功处理程序是:
function _handleSuccess(res:DescribeRulesOutput) {
console.log(`Get rules info: ${JSON.stringify(res.Rules,null,4)}`);
return res.Rules ;
}
因为我的错误处理程序总是会重新抛出,所以我永远不会收到响应。我的 IDE(VSCode)告诉我以下内容:
Type 'void | Rules' is not assignable to type 'Rules'.
Type 'void' is not assignable to type 'Rules'.ts
现在,如果我这样做了,let rules:Rules|void
那我可以,但这是一种好的做法吗?
解决方案
使用 async/await 和 Promise 是有区别的,它们是互斥的。在您的示例中,您可以执行以下操作(如果您想使用 async/await):
try {
let res:DescribeRulesOutput = await elb.describeRules(params).promise();
console.log(`Get rules info: ${JSON.stringify(res.Rules,null,4)}`);
return res.Rules;
} catch (e:AWSError) {
console.error(`Error getting rules info - [${e.code}] ${e.message}`);
throw(e)
}
elb.describeRules(params).promise().then(_handleSuccess).catch(_handleError);
错误消息告诉您您正在将 void 分配给规则。这是因为 void 是你的承诺链中最后一次调用的结果。希望有帮助。
可以在这里找到关于 async/await 与 promise 的好读物。
推荐阅读
- python - Python re:如何匹配任何数字,即使是逗号和小数点?
- c++ - 将具有复制构造的对象推入向量时无法避免复制
- julia - Julia:在给定时间内运行外部进程并捕获其输出
- go - Golang:为什么 strings.Builder.WriteByte API 建议它可以返回错误?
- node.js - 节点子进程bash脚本中的嵌套json参数
- java - 我在使用用户定义的函数时遇到问题
- c# - WMPLib 音乐播放,但是当我切换标签时它停止
- algorithm - 这段代码的时间复杂度是多少?
- node.js - 将pdf-fill-form部署到heroku的问题
- swift - 如果更改,如何在 SFSafariViewWrapper 中获取 URL