ESLint issues no-misused-promises where anonymous function used to await multiple async calls

2.5k views Asked by At

So I've been happily using these intermediary functions to wrap async operations that I need to operate sequentially. Such as "ensure sqlite db exists, then create opening schema" etc. I Just switched over to ESLint and I can't figure out what syntax it wants, and when I give it what I think it wants that still doesn't work and also doesn't compile. If I do the obvious thing and switch version2 to use Promise<boolean> then compilation fails with: src/dimTest.ts(23,13): error TS2322: Type 'void' is not assignable to type 'boolean'

Am I misunderstanding something about promises and just getting lucky that it works or is this an ESLint issue? Thanks!

/* eslint-disable no-console */
class test {
    constructor() {
        // ;
    }

    // this is what I originally used
    async version1():Promise<boolean> {
        return new Promise(async (resolve,reject) => {
            await this.delay(2000);
            await this.delay(500);
            await this.delay(250);
            resolve(true)
        });
    }

    // This method compiles but eslint is still says misused promise
    async version2(): Promise<boolean> {
        return new Promise(async (resolve, reject):Promise<any> => {
            await this.delay(2000);
            await this.delay(500);
            await this.delay(250);
            resolve(true);
        });
    }
    public async main(): Promise<void> {
        console.log("Hello!");
        await this.version1();
        console.log("Goodbye!");
        console.log("Hello!");
        await this.version2();
        console.log("Goodbye!");
    }

    protected delay(ms: number = 5000 ): Promise<number> {
        return new Promise((resolve) => { setTimeout(resolve, ms); });
    }
}
export { test };

const dt = new test();
void dt.main();
1

There are 1 answers

0
Shivam Pandey On BEST ANSWER

If the function is async then no need to return a promise,

async version1(): Promise<boolean> {
        await this.delay(2000);
        await this.delay(500);
        await this.delay(250);
        return true;
    }