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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.