Last active
April 18, 2020 04:39
-
-
Save phuctm97/a86238ba9f66e682a49e8b435a57401f to your computer and use it in GitHub Desktop.
Use Go Channels as Promises and Async/Await
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Javascript. | |
const longRunningTask = async () => { | |
// Simulate a workload. | |
sleep(3000) | |
return Math.floor(Math.random() * Math.floor(100)) | |
} | |
const r = await longRunningTask() | |
console.log(r) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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