Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async promise executor functions

I have a function that returns a Promise like this:

async function processFolder(folder) {
    return new Promise(async (res) => {
        const table = {};
        const list = await getHTMLlist(folder);
        if (list.length === 0) res(table);
        for (let i = 0; i < list.length; i++) {
            await processFile(folder, list[i], table);
        }
        res(table);
    });
}

I'm using ESLint that warn me:

"Promise executor functions should not be async" that is the no-async-promise-executor rule that throw an error due to the async keyword in the Promise declaration.

I have already fixed the same problem in other parts of the code where there was only one await inside the Promise using the technique suggested on this page of the ESLint documentation and showed in this answer, but in my use case I don't really know how to refactor the code in order to avoid that error. Any suggestions are welcome

like image 452
Plastic Avatar asked Aug 28 '26 15:08

Plastic


1 Answers

You don't need to create a new promise yourself because async functions always return a promise. If the return value of an async function is not a promise, it is implicitly wrapped in a promise.

So you need to remove the code that creates a new promise instance and the code inside the executor function should be at the top-level in the processFolder function.

Your code can be simplified as shown below:

async function processFolder(folder) {
    const table = {};
    const list = await getHTMLlist(folder);

    if (list.length > 0) {
       for (let i = 0; i < list.length; i++) {
           await processFile(folder, list[i], table);
       }
    }

    return table;
}

Ideally, you should also wrap the code inside the processFolder function in a try-catch block to catch and handle any errors that might occur during the execution of this function.

like image 82
Yousaf Avatar answered Aug 30 '26 20:08

Yousaf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!