Skip to content

Instantly share code, notes, and snippets.

@jakubriedl
Forked from phuctm97/1asyncawait.js
Last active March 30, 2022 02:45
Show Gist options
  • Save jakubriedl/ac70050a1df35955c1d7ba7357898aff to your computer and use it in GitHub Desktop.
Save jakubriedl/ac70050a1df35955c1d7ba7357898aff to your computer and use it in GitHub Desktop.
Use Go Channels as Promises and Async/Await
// 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)
// 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