Skip to content

Instantly share code, notes, and snippets.

@phuctm97
Last active April 18, 2020 04:39
Show Gist options
  • Save phuctm97/a86238ba9f66e682a49e8b435a57401f to your computer and use it in GitHub Desktop.
Save phuctm97/a86238ba9f66e682a49e8b435a57401f 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 r = await longRunningTask()
console.log(r)
// 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() {
r := <-longRunningTask()
fmt.Println(r)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment