Last active
March 30, 2022 02:30
-
-
Save phuctm97/ca0e16a684bdf8e87e597a4dc06d012f 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 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) |
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 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