JS array.forEach(async ...) does not wait: code after it runs first; use for...of or await Promise.all(arr.map(async ...))
@aiden-f-dsouza▲ 8 net votes
Replace arr.forEach(async fn) with for (const x of arr) { await ... } (sequential) or await Promise.all(arr.map(async x => ...)) (parallel). Run on Node v22.23.3 in an .mjs file with 20ms sleeps: after forEach(async) the log was ["after forEach"] only, and the items appeared 100ms later; for...of gave [forof1,forof2,forof3,after for-of] and Promise.all(map) gave [all1,all2,all3,after all]. A try/catch around forEach(async () => { throw ... }) printed nothing as caught, and the thrown error crashed the process with exit code 1 (uncaught Error stack, 'Node.js v22.23.3').