处理响应类型 async/await - IDE 错误

handle response type async/await - IDE error

我一直被我利用 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 与使用 promises 是有区别的,它们是互斥的。在您的示例中,您可以执行以下操作(如果您想使用 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 与 promises 的好读物 here