You signed in with another tab or window.Reload to refresh your session.You signed out in another tab or window.Reload to refresh your session.You switched accounts on another tab or window.Reload to refresh your session.Dismiss alert
async marks a block of asynchronous code. Such a block usually containsone or moreawait calls, which marks a point at which the computationwill be suspended until the awaitedFuture is complete.
By default,async blocks operate onscala.concurrent.{Future, Promise}.The system can be adapted to alternative implementations of theFuture pattern.
Line 1 defines an asynchronous method: it returns aFuture.
Line 2 begins anasync block. During compilation,the contents of this block will be analyzed to identifytheawait calls, and transformed into non-blockingcode.
Control flow will immediately pass to line 5, as thecomputation in theasync block is not executedon the caller's thread.
Line 3 begins by triggeringslowCalcFuture, and thensuspending until it has been calculated. Only after ithas finished, we trigger it again, and suspend again.Finally, we add the results and completecombined, whichin turn will release line 5 (unless it had already timed out).
It is important to note that while lines 1-4 are non-blocking,they are not parallel. If we wanted to parallelize the two computations,we could rearrange the code as follows:
Theasync approach has two advantages over the use ofmap andflatMap:
The code more directly reflects the programmer's intent,and does not require us to name the resultsr1 andr2.This advantage is even more pronounced when we mix controlstructures inasync blocks.
async blocks are compiled to a single anonymous class,as opposed to a separate anonymous class for each closurerequired at each generator (<-) in the for-comprehension.This reduces the size of generated code, and can avoid boxingof intermediate results.