I am learning node.js and I am confused about how async works. My understanding is that Array.foreach is blocking but then the below piece of code does not work as expected.
testfunc.ts:
export const testfunc = async (numArray: number[]) => {
let count = 0;
numArray.forEach(async (elem) => {
if (elem % 2 === 0) {
await new Promise((r) => setTimeout(r, 2000));
console.log(elem);
count = count + 1;
}
});
console.log(`printed ${count}`);
};
sendmessage.ts:
import { testfunc } from "./testfunc";
const callTestFunc = async () => {
await testfunc([1, 2, 3, 4, 5, 6]);
};
callTestFunc();
I was expecting an out put of:
2
4
6
printed 3
But, I am getting
printed 0
2
4
6
Can someone explain this to me.