nodejs / help

:sparkles: Need help with Node.js? File an Issue here. :rocket:
1.44k stars 276 forks source link

foreach async bug #4385

Closed billgan1024 closed 1 month ago

billgan1024 commented 2 months ago

Version

v20.12.2

Platform

No response

Subsystem

No response

What steps will reproduce the bug?

let src = ["src"]; let files = []; source.forEach(async (src) => { let found = await vscode.workspace.findFiles(${src}/**/*.cpp); files = files.concat(found); });

How often does it reproduce? Is there a required condition?

No response

What is the expected behavior? Why is that the expected behavior?

files is populated with the directories

What do you see instead?

files is empty

Additional information

No response

RedYetiDev commented 1 month ago

Hi! IIRC, forEach is not async, so what's probably happening is your array is full of promises. If you wrap your file array in Promise.all, said promises will be evaluated.

Also, this might be a problem with your VSCode, and not Node.js itself.

billgan1024 commented 1 month ago

Alright, that worked.

Also, this might be a problem with your VSCode, and not Node.js itself.

That's the pot calling the kettle black, isn't it? As far as I can tell, there's no easy way to convert async functions to be synchronous.

RedYetiDev commented 1 month ago

That's the pot calling the kettle black, isn't it? As far as I can tell, there's no easy way to convert async functions to be synchronous.

I was referring to the vscode.workspace.findFiles function, as in if my first suggestion didn't work.

billgan1024 commented 1 month ago

I see. My point was that the current async/await behaviour is so counterintuitive that discussions about it revolve around word-of-mouth and trial-and-error: https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop

RedYetiDev commented 1 month ago

I believe that TC39 handles the specification on asynchronous execution, so you may want to discuss this with them.