首页 > 解决方案 > 处理响应类型 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那我可以,但这是一种好的做法吗?

标签: typescriptaws-sdk-js

解决方案


使用 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 的好读物。


推荐阅读