Search code examples
typescriptaws-sdk-js

handle response type async/await - IDE error


I have been stumped by the scenario where I leverage a promise(then|catch) to handle errors, but also await for code cleanliness. The below is what I'm looking at:

let rules:Rules = await elb.describeRules(params).promise().then(_handleSuccess).catch(_handleError);

The error handler is:

function _handleError(e:AWSError) {
    console.error(`Error getting rules info - [${e.code}] ${e.message}`);
    throw(e)
}

The success handler is:

function _handleSuccess(res:DescribeRulesOutput) {
    console.log(`Get rules info: ${JSON.stringify(res.Rules,null,4)}`);
    return res.Rules ;
}

since my error handler will always rethrow, I should never receive a response. My IDE (VSCode) tells me the below:

Type 'void | Rules' is not assignable to type 'Rules'.
  Type 'void' is not assignable to type 'Rules'.ts

Now, if I do let rules:Rules|void then Im ok, but is this good practice?


Solution

  • There is a difference between using async/await vs promises, and they are mutually exclusive. In your example, you could do the following (if you want to use 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);
    

    The error message is telling you that you are assigning void to rules. This is because void is the result of the last call in your promise chain. Hope that helps.

    A good read on async/await vs promises may be found here.