fix IDE error when handling responses with async/await

I find myself facing a challenging scenario involving the use of promises (then|catch) for error handling, while also awaiting code cleanliness. Here's what I'm currently dealing with:

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

The error handler function is:

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

The success handler function is:

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

Since my error handler always rethrows, theoretically I should not receive a response. However, my IDE (VSCode) displays the following message:

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

Considering this issue, if I change let rules:Rules|void everything works fine. But my question is, is this considered good practice?

Answer №1

When it comes to using async/await versus promises, it's important to note that they are mutually exclusive concepts. In the provided example, you have the option to utilize async/await in the following manner:

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 indicates that void is being assigned to rules. This occurs because void is the result of the last call in your promise chain. I hope this explanation clarifies things for you.

If you're interested in learning more about the differences between async/await and promises, I recommend checking out this informative article.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discovering Angular: A Guide to Displaying Dropdown Items in Dropdown Buttons

I'm seeking guidance on dropdown buttons. Here is some code I found in an example: <!--adjustbtn is a class I created to style the button--> <button class="dropdown adjustbtn" style="border-radius: 5px; box-shad ...

When working with Typescript and Vue.js, it's important to ensure that properties are initialized before

Check out the following code snippet: export default class PrimitiveLink extends Vue { style = { // Reset display: 'inline-block', textDecoration: 'none', outline: 'none', // Theme ...this.themeStyle ...

The type 'MutableRefObject<undefined>' cannot be assigned to the type 'LegacyRef<HTMLDivElement> | undefined'

I have created a customized hook that takes a ref object and observes its behavior: import { useState, useEffect, MutableRefObject } from "react"; const UseOnScreen = (ref: MutableRefObject<undefined>) => { const [isIntersecting, setI ...

Generating distinct identifiers for WebSocket and net.Socket connections

I am looking to assign unique identifiers to Websockets and net.Sockets so that each client can be identified by the identifier attached to the socket when a message is received. Previous findings: For WebSocket: Based on my research on Stack Overflow a ...

Having trouble reloading a seekbar (input range) in Angular 7 with a function?

I am currently in the process of developing a music player using Angular 7, and below is the HTML code for my component: <div class="track-controller"> <small>{{musicPlayerService.getCurrentTime()}}</small> <div class="progress- ...

The source files are expected to be contained within the 'rootDir' directory, which is not located at 'c:/Users/hasit/Desktop/typescript/src'

Can someone assist me with separating the Src folder and public folder in my project? When I try to do it in the tsconfig.json file, I encounter this error: "'rootDir' is expected to contain all source files." I have followed instructions from a ...

Develop customizable enumerations for use in expandable interfaces

Situation: My objective is to devise a strategy for building scalable state machines in TypeScript using the TypeState library. TypeState offers a typesafe state machine for Typescript, which while not directly related to my current issue, serves as a good ...

Issue with TypeScript version 4.2.1 - The Array.some() method does not support a function that returns a boolean

I encountered a TypeScript error that goes as follows: https://i.sstatic.net/RoGER.png The complete error message reads: Supplied parameters do not match any signature of call target: parameter type mismatch. > Parameter 'Predicate' should ...

Receiving an error when triggering an onclick event for a checkbox in TypeScript

I am creating checkboxes within a table using TypeScript with the following code: generateTable(): void { var table = document.getElementById("table1") as HTMLTableElement; if (table.childElementCount == 2) { for (var x = 0; x < 2; x++) ...

Tips for managing Vue component content prior to data being fully loaded

I'm currently integrating product category data from Prismic into my Nuxt project and seeking guidance on best practices. Specifically, I need clarity on managing the state when data is still being fetched and there's no content to display in the ...

Rendering Information in Angular 4 Through Rest API

Encountering issues displaying data from my local express.js REST API, organized as follows: people: [{ surname: 'testsurname', name: 'testname', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemai ...

Is it possible to integrate a collection of libraries along with external dependencies into Vite?

Currently, I am in the process of packaging a library for npm that uses type: "module". To accomplish this, I have configured vite's library mode with the following settings: export default defineConfig({ css: { postcss: { plugin ...

What is the process of defining a TypeScript AWS Lambda handler for Lambda Function URLs?

The npm package @types/aws-lambda provides TypeScript declarations for different ways Lambda functions can be triggered. For instance, when triggering the Lambda function through API Gateway, you can use the following code snippet: import { APIGatewayProxy ...

The node command line does not recognize the term 'require'

My Typescript project was compiling and running smoothly until recently when I started encountering the error ReferenceError: require is not defined every time I try to run node. I am uncertain whether this issue stems from Typescript, as even when I ru ...

Angular 6 does not automatically include the X-XSRF-TOKEN header in its HTTP requests

Despite thoroughly reading the documentation and searching for answers on various platforms, I am still facing issues with Angular's XSRF mechanism. I cannot seem to get the X-XSRF-TOKEN header automatically appended when making a POST request. My si ...

Configuring global runtime variables in NextJS for server-side operations

Currently, I am utilizing the instrumentation.ts file in NextJS to retrieve configuration dynamically when the server starts up. My goal is to have this configuration accessible during runtime for all API routes and server-side components. What would be th ...

Ways to simulate a variable imported in the module being tested without it being a function parameter can be achieved by using describe.each and changing the mock value for each test

I have a requirement to test a function within my TypeScript module. module-to-test.ts import { config } from './app-config'; export const isSomethingWhatINeedSelector = createSelector( firstDependencySelector, secondDependencySelector ...

How can I convert the date format from ngbDatepicker to a string in the onSubmit() function of a form

I'm facing an issue with converting the date format from ngbDatepicker to a string before sending the data to my backend API. The API only accepts dates in string format, so I attempted to convert it using submittedData.MaturityDate.toString(); and su ...

Database is not displaying the many-to-many connections

Good morning! Hey everyone, I'm having an issue with my code that I need help solving. It involves a many-to-many relationship where users can subscribe to items. user.entity.ts @Entity("user") export class UserEntity { @PrimaryGeneratedColumn ...

The React DOM isn't updating even after the array property state has changed

This particular issue may be a common one for most, but I have exhausted all my options and that's why I am seeking help here. Within my React application, I have a functional component named App. The App component begins as follows: function App() ...