dvlsg / async-csp

CSP style channels using ES7 async/await
MIT License
317 stars 18 forks source link

Real-world practical examples. #21

Open trusktr opened 6 years ago

trusktr commented 6 years ago

It'd be great if we can add to the docs (README) some real-world practical examples (f.e. like @rauschma's example if .filter() were part of async-csp).

Seeing the API docs may not help to know when/how to apply those APIs. Axel's example shows how to take async-csp and what it could really be good for.

In some cases, I've been trying to use async-csp to solve a problem, but ended up just removing it in favor of a Promise-only solution. I feel like async-csp can help bring clear solutions to async problems, but I'm just not entirely clear when/where yet.

If I come up with any of my own use cases, I'll make PRs with examples.

My use cases, at the moment, are all graphical-programming-related, not really server side filesystem stuff like in Axel's example where it is clear how async-csp is really helpful there when there's obviously file chunks that can be though of as async pieces that can go through a channel.

trusktr commented 6 years ago

For example, in my use cases, I might want to watch the size of an object. Here's two ways to do it, with channels, and with events:

        // channels
        async watchSize ( node ) {
            this.watchingSize = true
            while ( this.watchingSize ) {
                const size = await node.actualSize.take()
                // do something with size.
            }
        }
        unwatchSize () {
            this.watchingSize = false
        }
        // events
        watchSize ( node ) {
            this.watchingSize = () => {
                const size = node.actualSize
                // do something with size.
            }
            node.actualSize.on('change', this.watchingSize)
        }
        unwatchSize ( node ) {
            node.actualSize.off(this.watchingSize)
        }

They're both roughly the same complexity as far as written code, but I've opted to go with events in this case because I can coordinate them in the same tick with less performance overhead of async functions and promises.

Maybe this use case isn't a good example of when to use Channels (though I like the concept of how the while loop is written despite more overhead).