ESLint flags a misuse of promises in my code that I believe is acceptable

This symbol table implementation includes a method that needs some adjustments:

    public getAllSymbols(type?: typeof Symbol, localOnly = false): Promise<Set<Symbol>> {
        const promise = super.getAllSymbols(type ?? Symbol, localOnly);

        return new Promise(async (resolve, reject) => {
            try {
                let result = await promise;

                if (!localOnly) {
                    this.dependencies.forEach(async (dependency) => {
                        result = new Set([...result, ...await dependency.getAllSymbols(type, localOnly)]);
                    });
                }

                resolve(result);
            } catch (reason) {
                reject(reason);
            }
        });
    }

Although this code is functional, ESLint raises concerns about 2 promise misuses:

https://i.stack.imgur.com/1Z2fF.png

The linter error indicates a "Promise returned in function argument where a void return was expected. no-misused-promises".

To address this issue and eliminate the linting error, we need to make some modifications to the code structure.

Answer №1

The issues in your code:

  • Avoid making the Executor function async as it is considered an anti-pattern

  • No need to wrap the promise returned by super.getAllSymbol(...) in a promise constructor - this is another anti-pattern. Directly call the then() method on the promise.

  • Do not use async-await with forEach() as it will not wait for promises to settle before moving to the next iteration. Instead, consider using Promise.all() with map().

Your revised code (types removed for simplicity):

public getAllSymbols(type, localOnly = false) {

     const promise = super.getAllSymbols(type ?? Symbol, localOnly);

     return promise
         .then(result => {
             if (!localOnly) {
                 return Promise.all(this.dependencies.map(dep => (
                    dep.getAllSymbols(type, localOnly))
                 )))
                 .then(resultArr => {
                     return new Set([...result, ...resultArr]);
                 });
             }
             else {
                 return result;
             }                       
         });
}

Alternatively, you can use the async-await syntax:

public async getAllSymbols(type, localOnly = false) {

    const result = await super.getAllSymbols(type ?? Symbol, localOnly);

    if (!localOnly) {
        const resultArr = await Promise.all(this.dependencies.map(dep => ( 
            dep.getAllSymbols(type, localOnly)
        )));

        return new Set([...result, ...resultArr]);                         
    }

    return result;                   
}

I have omitted the catch block assuming error handling should be done by the calling code.

To call the above function:

getAllSymbols(...)
   .then(result => { ... })
   .catch(error => { ... });

or using async-await:

try {
    const result = await getAllSymbols(...);
    // handle success
   
} catch (error) {
    // handle error
}
      

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

Here's a helpful guide on verifying the presence of a value within an array in Quasar

const myproducts = ref([]) const items = ref([ { id: 1, item: 'Vaporub 50Gm' , barcode: '123456'}, { id: 2, item: 'Herbal Cool Oil (300+100)Ml', barcode: '123456' }, { id: 3, item: 'live Oil Bp 70M ...

Unleashing the power of scroll-based dynamic pagination in ReactJS

I have 33 entries in a json format. I've implemented a code that tracks the scroll on my page and loads new 10 entries at a time. Everything works smoothly when the scroll value is set to equal or less than zero. When the scroll reaches the bottom of ...

Angular 2: Applying class to td element when clicked

I am working with a table structured like this <table> <tbody> <tr *ngFor="let row of createRange(seats.theatreDimension.rowNum)"> <td [ngClass]="{'reserved': isReserved(row, seat)}" id={{row}}_{{sea ...

The problem with the first item title in the Jquery slider is causing

I've been working on setting up a Jquery slider (caroufredsel) in which I want certain elements to be displayed above the slider itself, outside of the wrapper. Everything is working fine except for the first slide! After spending several days trying ...

I can't figure out why this form isn't triggering the JS function. I'm attempting to create an autocomplete form field that connects to a MySQL database using a PHP script and AJAX

I am encountering an issue while trying to implement the .autocomplete() function from jQuery UI with a list of usernames fetched from a MySQL database using a PHP script. Strangely, it is not functioning as expected and no errors are being displayed in th ...

Make sure to load the gif image before any other images are loaded from the css

Hey there, I'm attempting to display a GIF image before the actual image loads. I found a great example to accomplish this: Example: Java Script function loadimage(imgsrc, change){ var loadimage = new Image(); loadimage.onload = changesrc(imgsrc, c ...

JavaScript: Incorporating an operator into a specific object (instead of the entire class)

Are you familiar with how to include an operator in an object (rather than the entire class)? When it comes to a method, I know you can achieve that by: my_object.new_function = function(){return 1}; Then invoking my_object.new_function() will output ...

What is the process for applying the source from an object while utilizing video-js?

I've been struggling to use a video player for streaming m3u8 videos. The code below works, but I want to dynamically set the source using an object. <video id="my-video" class="video-js" auto ...

Guide on setting up the installation process of Gulp jshint with npm?

Having trouble with the installation of JSHint. Can anyone point out what I might be doing incorrectly? This is the command I am using: npm install --save-dev gulp-jshint gulp-jscs jshint-stylish Getting the following error message: "[email protect ...

Use PHP to transform an array into JSON format, then access and retrieve the JSON data using either jQuery or JavaScript

I have successfully generated JSON data using PHP: $arr = []; foreach($userinfo as $record) { $arr[] = array( 'BAid' => $record->getBAid(), 'BCid' => $record->getBCid(), 'BA ...

Issues with Three.js raycaster intersectObjects

I am currently working on a 3D scatter plot where spheres are used to represent the points, and I am attempting to show information from the points when they are clicked. After researching various answers on this platform, I believe I am moving in the righ ...

The process of generating vue-cli-plugin-prerender-spa encountered an issue where the error was not found within the

I have successfully integrated this plugin into my laravel-vue application and configured it within the laravel mix's webpack.mix.js file. After running it via npm (using watch, dev, and prod modes), I encountered no errors. However, upon inspecting ...

What is the best way to set a default value for a specified Date format retrieved from an API?

Here are examples of different data formats for ReleaseDate: 2014-09-23 09:00:00.923Z /Date(1407369600210)/ If you want to access this information from an API, you can use the following object dot-notation: result.data.Items[0].ReleaseDate Sometimes, ...

What is the best way to access the URLs of files within a Google Drive folder within a React application?

I've been working on a react app that's relatively straightforward, but I plan to add a gallery feature in the future. To keep things simple for the 'owner' when updating the gallery without implementing a CMS, I decided to experiment ...

Exploring the world of JMeter: capturing sessions with JavaScript and jQuery

I need to capture a user session in order to conduct a performance test. I have been using the JMeter HTTP(S) Test Script Recorder, but unfortunately it is not recognizing javascript and jquery. The error message I'm receiving is: JQuery is not def ...

Issues with loading an external CSS file in an HTML document

I've been attempting to implement a loading animation using jQuery, but I'm encountering issues with loading the CSS file. I have tried various paths for the css file such as: <link href="css/animation.css" type="text/css" rel="stylesheet"> ...

Retrieving a JSON object using a for loop

I'm working on a basic link redirector project. Currently, I have set up an Express server in the following way: const express = require('express'); const app = express() const path = require('path'); const json = require('a ...

Steps for displaying a loading image during the rendering of a drop-down list (but not during data loading):

Using jQuery's autocomplete combobox with a large dataset of around 1,000 items. The data loads smoothly from the server, but there is a delay when expanding the drop-down list to render on screen. Is there a way to capture the initial click event on ...

What is the best way to calculate the sum of table data with a specific class using jQuery?

If I had a table like this: <table class="table questions"> <tr> <td class="someClass">Some data</td> <td class="someOtherclass">Some data</td> </tr> <tr> <td class="s ...

The lack of intellisense in VS Code for Node.js poses a significant challenge for developers

I am facing a problem with IntelliSense in Visual Studio Code. Despite installing multiple extensions, it is not working as expected. The IntelliSense feature only shows functions and variables that have already been used in my code file. Below is the li ...