Skip to content

Instantly share code, notes, and snippets.

@phuctm97
Last active October 7, 2019 14:47
Show Gist options
  • Save phuctm97/482b9c888c1e44943951925480a960f0 to your computer and use it in GitHub Desktop.
Save phuctm97/482b9c888c1e44943951925480a960f0 to your computer and use it in GitHub Desktop.
Use Go Channels as Promises and Async/Await
// Javascript.
const longRunningTask = async () => {
// Simulate a workload.
sleep(3000)
return Math.floor(Math.random() * Math.floor(100))
}
const [a, b, c] = await Promise.all(longRunningTask(), longRunningTask(), longRunningTask())
console.log(a, b, c)
// Go.
package main
import (
"fmt"
"math/rand"
"time"
)
func longRunningTask() <-chan int32 {
r := make(chan int32)
go func() {
defer close(r)
// Simulate a workload.
time.Sleep(time.Second * 3)
r <- rand.Int31n(100)
}()
return r
}
func main() {
aCh, bCh, cCh := longRunningTask(), longRunningTask(), longRunningTask()
a, b, c := <-aCh, <-bCh, <-cCh
fmt.Println(a, b, c)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment