Add example to coroutines post
This commit is contained in:
parent
46eccf2c4d
commit
d08bb6dd10
1 changed files with 32 additions and 0 deletions
|
@ -23,6 +23,38 @@ If we think of a normal function, the way it works is that we **call** the funct
|
||||||
|
|
||||||
In a similar way, a very simple coroutine will do the same thing: We will **create** the coroutine, it will **execute** and at some point it will end and (implicitly) **yield** back to the calling code.
|
In a similar way, a very simple coroutine will do the same thing: We will **create** the coroutine, it will **execute** and at some point it will end and (implicitly) **yield** back to the calling code.
|
||||||
|
|
||||||
|
Here is a simple example of how this looks in practice.
|
||||||
|
|
||||||
|
First we define a new coroutine that yields three times and finally prints "Done"
|
||||||
|
|
||||||
|
```js
|
||||||
|
my_coro = coroutine(=> {
|
||||||
|
yield(1)
|
||||||
|
yield(2)
|
||||||
|
yield(3)
|
||||||
|
print("Done")
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Now we can resume the coroutine up to 4 times, and each time it will resume from the last `yield` and stop at the next one, or when it reaches the end of the function.
|
||||||
|
|
||||||
|
```
|
||||||
|
first_yield = resume(coro)
|
||||||
|
// At this point the coroutine is paused on its first line
|
||||||
|
print(first_yield) // prints 1
|
||||||
|
|
||||||
|
second_yield = resume(coro)
|
||||||
|
// At this point the coroutine is paused on its second line
|
||||||
|
print(second_yield) // prints 2
|
||||||
|
|
||||||
|
third_yield = resume(coro)
|
||||||
|
// At this point the coroutine is paused on its third line
|
||||||
|
print(third_yield) // prints 3
|
||||||
|
|
||||||
|
resume(coro) // prints "Done"
|
||||||
|
// At this point the coroutine has completed its execution.
|
||||||
|
```
|
||||||
|
|
||||||
The big difference is: A coroutine can **yield** more than once, and will be paused in between. And that is really all there is to them, from a technical level. A simple example of this would look like this.
|
The big difference is: A coroutine can **yield** more than once, and will be paused in between. And that is really all there is to them, from a technical level. A simple example of this would look like this.
|
||||||
|
|
||||||
## Classifying Coroutines
|
## Classifying Coroutines
|
||||||
|
|
Loading…
Reference in a new issue