do chan.select defaults work?
basically the default cases here: https://gobyexample.com/non-blocking-channel-operations
couldn't really see anything from the code, but in the original PR with the switch statement makes me think that it's possible
Not currently, but its funny that you asked me about this, because I was working on supporting default in selects just a couple hours earlier. I am back to working on a v1 release that will have a few API changes, and selects were always a little but awkward so I wanted to revisit that as part of the change.
Chan will have an API similar to core/async's alts as well as a select DSL that is similar to go. The new select DSL will have support for default and will look something like this:
await chan.select(
ch1, val1 => {
console.log(val1)
},
ch2, val2 => {
console.log(val2)
},
default => {
console.log('ch1 and ch2 are empty')
}
)
The select function take a variable number of arguments which alternate channels and callbacks. If there is an odd number or arguments it is assumed that the last argument is a default callback, and the behavior should match the default cause in a go select statement. The default callback does not receive any arguments, but in my example I had a param named default to add clarity. default will be undefined in the callback. Using that convention would be optional.
Thoughts? I have people waiting for chan to use promises instead of thunks (another part of the v1 refactor) so it shouldn't be too long before this is ready to be used.
Well... I guess not default since it is a reserved word. That was just something I thought of as I was writing out the example. My brain isn't working yet this morning. I still like calling it out somehow. ¯(ツ)/¯,
see 16db99b1adb41c8a9fe2007760c746af70101303
I haven't written tests yet, so this could be broken, but it is the general idea.
awesome! i'd personally go with one or the other if they're functionally equivalent. i think the expression syntax is a bit more powerful in core.async since you can dynamically set the switches at runtime, but totally your call.
It's a bit tough to derive a usage example just by looking at the code, but I'd imagine you could do something like this with new JS syntax:
await chan.select({
ch1,
val1() { console.log(val1) },
ch2,
val2() { console.log(val2) },
default() { console.log('nothing on the channel') }
})
also, i think with core.async you can wait on both the put and the take so maybe the usage looks more like this:
await chan.select({
ch1.take(),
val1() { console.log(val1) },
ch2.put('hi'),
val2() { console.log(val2) },
default() { console.log('nothing on the channel') }
})
also, i really liked the thunk implementation, but i guess we're all moving to promises haha.