For the following code, I expect each promise to be started and run. I do not expect the promises to be awaited until the end of the code, and yet for some reason, each operation is run synchronously. Why is this? Am I simply doing something wrong?
#!/usr/bin/env node
const longRunningOperation = async (index) =>{
console.log("Starting Operation " + index.toString())
console.time(index)
const cap = 5_000_000_000;
let sum = 0
for(let i = 0; i < cap; i++) sum+=i
console.timeEnd(index)
}
const op1 = longRunningOperation(1);
const op2 = longRunningOperation(2);
const op3 = longRunningOperation(3);
const op4 = longRunningOperation(4);
console.log("Hi! I run before anything else. Right?")
await Promise.all([op1, op2, op3, op4])
Actual Result:
Starting Operation 1
1: 4.336s
Starting Operation 2
2: 4.740s
Starting Operation 3
3: 11.830s
Starting Operation 4
4: 11.675s
Hi! I run before anything else. Right?
Expected Result (times varying of course):
Hi! I run before anything else. Right?
Starting Operation 1
Starting Operation 2
Starting Operation 3
Starting Operation 4
1: 4.336s
2: 4.740s
3: 11.830s
4: 11.675s