TSLint now requires promises to be handled correctly using the `finally` clause

Encountering an error from TSLint, I am working to comprehend why it is raising concerns.

In my code, there is a function that calls another method which returns a promise. However, the initial function does not return the promise; instead, it waits for completion and updates an internal state.

To simplify the scenario, here is a snippet using Q() to simulate a promise-invoking call:

export function DoSomethingAsync(): void {
    Q().then(r => {
        console.log('test');
    }).catch(err => {
        log.error("wow");
    }).finally(() => {
        log.info("at finally")
    });
}

Upon running tslint, the following error surfaces:

ERROR: C:/dev/local_cache_service.ts[31, 5]: Promises must be handled appropriately

Eliminating the finally block allows TSLint to complete without errors:

export function DoSomethingAsync(): void {
    Q().then(r => {
        console.log('test');
    }).catch(err => {
        log.error("wow");
    });
}

Interestingly, this issue does not occur when implementing the same function in a seed TypeScript project...

Answer №1

This message pertains to the guideline outlined in the no-floating-promises rule. The rule emphasizes the importance of handling Promises properly.

The rule warns against creating a Promise without storing or returning it, as this can cause unexpected behavior due to timing factors. It recommends returning Promises from functions that initiate them and handling them in the calling code.

To identify more floating promises, consider using the no-unused-expression rule alongside this one.

In your specific case, the issue is related to executing code inside a .finally block after the .catch block. Following this pattern could lead to unhandled errors if an exception occurs within the .finally block.

The recommended solution is to ensure the function's return type is a Promise by properly returning the promise instead of a void.

For additional insights, you can utilize tslint -t stylish or tslint -t verbose options to view rule names along with their corresponding feedback!

Answer №2

To solve the problem, it was necessary to include a .done() call after completing the promise chain.

If I'm interpreting correctly, using done will transform any unhandled exceptions into a standard unhandled exception.

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

Strategies for effectively choosing this specific entity from the repository

Is it possible to choose the right entity when crafting a repository method using typeorm? I'm facing an issue where I need to select the password property specifically from the Admin entity, however, the "this" keyword selects the Repository instead ...

Incorporate a JavaScript script into an Angular 9 application

I have been experiencing issues trying to add a script.js file to angular.json and use it in one component. Adding a script tag directly to my HTML file is not the ideal solution. Can someone suggest an alternative approach or point out what I may be missi ...

I am having trouble with the Primeng password template suggestions not appearing as expected

The demonstration available at this link is not functioning correctly, unlike the example provided in the documentation at this website. In the StackBlitz demo, the suggestions are not being displayed as expected for the password template. Take a look at ...

Nestjs struggles with resolving dependencies

Having trouble finding the issue in my code. (I'm still new to nestjs and trying to learn by working on some apps). The console log is showing the following error: Nest can't resolve dependencies of the UrlsAfipService (?). Please ensure tha ...

Obtain a tuple of identical length from a function

I'm attempting to create a function that returns a tuple with the same length as the parameter tuple passed to it. Although I tried using generics, I am encountering an error when applying the spread operator on the result. My goal is best illustrate ...

Using Angular CLI with ES6 instead of TypeScript for your development needs can offer a

Is there a way to utilize an ES6 transpiler such as Babel instead of TypeScript in an Angular CLI project? Are there any specific flags for specifying the script language, similar to using --style? Thank you. ...

How can I save a TypeScript object to Firebase using serialization?

Having an issue: Within my angular application, I have implemented a lot of classes with inheritance. However, upon attempting to save these objects to Firebase, I encountered an error indicating that I am trying to persist custom objects which is not supp ...

Using interfaces for typecasting in TypeScript

Consider the code snippet below: let x = { name: 'John', age: 30 } interface Employee { name:string, } let y:Employee = <Employee>x; console.log(y); //y still have the age property, why What is the reason for TypeScript ov ...

Can an Angular application be developed without the use of the app-root tag in the index.html file?

I'm a newcomer to Angular and I'm trying to wrap my head around how it functions. For example, if I have a component named "login", how can I make Angular render it directly? When I try to replace the app-root tag with app-login in index.html, n ...

Blend the power of Node's CommonJS with the versatility of Typescript's ES modules

I currently have a Node.js v10 legacy application that was built using CommonJS modules (require). The entire codebase is written in JavaScript. However, I am considering upgrading the app and refactoring a specific part of it to use TypeScript modules ( ...

TypeScript - Converting into individual compiled files

Currently, I am working on a project that consists of lengthy source files. While this is advantageous for imports, it poses challenges in terms of maintenance. For instance: /main/core.ts export type Foo { ... } export interface Bar { ... } export cla ...

What is the best way to display user data exclusively in Angular?

How can I ensure that users only have access to their own information rather than the entire database? I attempted to use an if-else statement to filter out the data I need, as shown in the example below, but it was unsuccessful. custom-history.component ...

JSX tags without any inner content should be self-closed

After successfully running this code, I encountered an issue when committing it to git. The error message 'ERROR: src/layouts/index.tsx:25:9 - JSX elements with no children must be self-closing' appeared. I attempted to resolve the error by addi ...

Can a VS Code theme extension be designed using JavaScript or TypeScript rather than JSON?

Currently working on a VS Code theme extension, I am interested in exploring the possibility of using JavaScript or TypeScript files instead of a JSON file. The idea of having all the theme information crammed into one massive JSON file feels disorganize ...

Exploring the generalization of class member initialization in TypeScript

I am looking to make some modifications to the Blog constructor provided in the "Minimal working example" linked below. The objective is to refactor it using pseudo-code by leveraging a generic ModelHelper class to initialize the members of the "Blog" clas ...

What is the best way to filter and sort a nested tree Array in javascript?

Looking to filter and sort a nested tree object for a menu If the status for sorting and filtering is true, how do I proceed? const items = [{ name: "a1", id: 1, sort: 1, status: true, children: [{ name: "a2", id: 2, ...

The side menu fails to appear when pressed

When using the push method, I am unable to see the side menu. However, it works fine with the setRoot navigation. How can I resolve this issue and display the side menu when using the push method? dashboard.html <ion-col col-9> <ion-searchbar ...

Encountering a premature closure error, specifically the inability to set headers after they have already been sent to the client, when trying to stream video

I am in the process of constructing a video streaming web server with Nestjs. I have diligently followed the steps outlined in the Nest documentation. Unfortunately, I encountered some errors... MY file.controller.ts import { Controller ...

When the promise is resolved, the members of the AngularJS controller are now

I'm experiencing some unexpected behavior in my controller when executing a certain method. The code snippet looks something like this: this.StockService.GetByInvoicesID(this.SelectedInvoice.ID).success((StockItems) => { this.StockItems = Stoc ...

Tips on transforming Angular 2/4 Reactive Forms custom validation Promise code into Observable design?

After a delay of 1500ms, this snippet for custom validation in reactive forms adds emailIsTaken: true to the errors object of the emailAddress formControl when the user inputs [email protected]. https://i.stack.imgur.com/4oZ6w.png takenEmailAddress( ...