|
25 | 25 | the tasklet, any yield of a Future waits for and returns the Future's result. |
26 | 26 | For example:: |
27 | 27 |
|
| 28 | + from from google.cloud.ndb.tasklets import tasklet |
| 29 | +
|
28 | 30 | @tasklet |
29 | 31 | def foo(): |
30 | | - a = yield <some Future> |
31 | | - b = yield <another Future> |
| 32 | + a = yield <AFuture> |
| 33 | + b = yield <BFuture> |
32 | 34 | return a + b |
33 | 35 |
|
34 | 36 | def main(): |
35 | 37 | f = foo() |
36 | 38 | x = f.result() |
37 | 39 | print x |
38 | 40 |
|
| 41 | +In this example, `foo` needs the results of two futures, `AFuture` and |
| 42 | +`BFuture`, which it gets somehow, for example as results of calls. |
| 43 | +Rather than waiting for their values and blocking, it yields. First, |
| 44 | +the tasklet yields `AFuture`. The event loop gets `AFuture` and takes |
| 45 | +care of waiting for its result. When the event loop gets the result |
| 46 | +of `AFuture`, it sends it to the tasklet by calling `send` on the |
| 47 | +iterator returned by calling the tasklet. The tasklet assigns the |
| 48 | +value sent to `a` and then yields `BFuture`. Again the event loop |
| 49 | +waits for the result of `BFuture` and sends it to the tasklet. The |
| 50 | +tasklet then has what it needs to compute a result. |
| 51 | +
|
| 52 | +The tasklet simply returns its result. (Behind the scenes, when you |
| 53 | +return a value from a generator in Python 3, a `StopIteration` |
| 54 | +exception is raised with the return value as its argument. The event |
| 55 | +loop catches the exception and uses the exception argument as the |
| 56 | +result of the tasklet. This won't work for Python 2. If you need to |
| 57 | +support Python 2, as the library itself does, you'll need to raise a |
| 58 | +`google.cloud.ndb.tasklets.Return` exception, with the return value as |
| 59 | +the exception argument, as in `google.cloud.ndb.tasklets.Return(a + |
| 60 | +b)`.) |
| 61 | +
|
39 | 62 | Note that blocking until the Future's result is available using result() is |
40 | 63 | somewhat inefficient (though not vastly -- it is not busy-waiting). In most |
41 | 64 | cases such code should be rewritten as a tasklet instead:: |
|
0 commit comments