Last active
October 7, 2019 14:47
-
-
Save phuctm97/482b9c888c1e44943951925480a960f0 to your computer and use it in GitHub Desktop.
Use Go Channels as Promises and Async/Await
This file contains hidden or 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 [a, b, c] = await Promise.all(longRunningTask(), longRunningTask(), longRunningTask()) | |
console.log(a, b, c) |
This file contains hidden or 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() { | |
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