4 ms·
I'm not sure I agree. In the first example `await` is added before the Future creation and this causes immediate execution in the printed output (second versio
by pests 8y ago
I'm not sure I agree.
In the first example `await` is added before the Future creation and this causes immediate execution in the printed output (second version). In the first version both Futures are pushed onto the EventTask queue and are executed after main() has finished.
In the second example with method1 and method2, in method1 with async (which signals a Future) on the forEach, all three Futures are pushed to the EventLoop queue and execute after method1() has finished. In method2() there is no new Future being added and execution happens immediately with the end of method2 executing after all delayedPrints.
You also see the effect with all three Futures resolving at once in the method1 case due to all three being added to the queue at the same time each with the same delay. Whereas with method2 each print with a delay after due to this function being synchronous with nothing going on the EventLoop.
- tylerhou 8y agoAwait pushes your task onto the end of the event queue; this might seem like you’re immediately executing a future in many cases but it’s not true in all cases. Other futures created by your thread might take priority. Consider the case where you pushed a future onto the event loop which infinite loops before you used await. Then your code will freeze.