Skip to content

Instantly share code, notes, and snippets.

@phuctm97
Last active March 30, 2022 02:30
Show Gist options
  • Save phuctm97/ca0e16a684bdf8e87e597a4dc06d012f to your computer and use it in GitHub Desktop.
Save phuctm97/ca0e16a684bdf8e87e597a4dc06d012f to your computer and use it in GitHub Desktop.
Use Go Channels as Promises and Async/Await
// Javascript.
const one = async () => {
// Simulate a workload.
sleep(Math.floor(Math.random() * Math.floor(2000)))
return 1
}
const two = async () => {
// Simulate a workload.
sleep(Math.floor(Math.random() * Math.floor(1000)))
sleep(Math.floor(Math.random() * Math.floor(1000)))
return 2
}
const r = await Promise.race(one(), two())
console.log(r)
// Go.
package main
import (
"fmt"
"math/rand"
"time"
)
func one() <-chan int32 {
r := make(chan int32)
go func() {
defer close(r)
// Simulate a workload.
time.Sleep(time.Millisecond * time.Duration(rand.Int63n(2000)))
r <- 1
}()
return r
}
func two() <-chan int32 {
r := make(chan int32)
go func() {
defer close(r)
// Simulate a workload.
time.Sleep(time.Millisecond * time.Duration(rand.Int63n(1000)))
time.Sleep(time.Millisecond * time.Duration(rand.Int63n(1000)))
r <- 2
}()
return r
}
func main() {
var r int32
select {
case r = <-one():
case r = <-two():
}
fmt.Println(r)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment