-
-
Save jakubriedl/ac70050a1df35955c1d7ba7357898aff 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 timeout3s(data) <-chan int32 { | |
r := make(chan int32) | |
go func() { | |
defer close(r) | |
// Simulate a workload. | |
time.Sleep(time.Millisecond * time.Duration(3000)) | |
r <- data | |
}() | |
return r | |
} | |
func callUpstream() <-chan int32 { | |
r := make(chan int32) | |
go func() { | |
defer close(r) | |
data, err = fetchData() | |
writeToDb(data) | |
r <- data | |
}() | |
return r | |
} | |
// 4s | |
func main() { | |
var r int32 | |
fromDB, err = readFromDB() | |
if(fromDB.createdAt < 60*1000) { // old = false | |
return fromDB | |
} | |
select { | |
case r = <-timeout3s(fromDB): | |
case r = <-callUpstream(): | |
} | |
return r | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment