For people accustomed to using Javascript, they have certainly used or heard about async / await, it is a feature of the language that allows working with asynchronous programming.
Golang has channels and goroutines, allowing this to be used very smoothly, however, people who have just come to the language may not know how to do it, to have a base, I prepared an example that can help to understand.
We will use the public pokeapi api.
How it is done in Javascript
const awaitTask = async () => {
let response = await fetch('https://pokeapi.co/api/v2/pokemon/ditto');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response
}
awaitTask()
.then(r => r.json())
.then(r => console.log(r))
How we do it in Golang
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
func awaitTask() <-chan string {
fmt.Println("Starting Task...")
c := make(chan string)
go func() {
resp, err := http.Get("https://pokeapi.co/api/v2/pokemon/ditto")
if err != nil {
log.Fatalln(err)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
c <- string(body)
fmt.Println("...Done!")
}()
return c
}
func main() {
value := <-awaitTask()
fmt.Println(value)
}
How to make:
- Set the return type to be a channel.
- Create a channel to return a value.
- Add a go func for asynchronous execution.
- Within the function, assign the value to the channel.
- At the end of the function, indicate the return of the channel with the value.
- In the main function, assign the return of the channel to a variable.
I appreciate everyone who has read through here, if you guys have anything to add, please leave a comment.
Top comments (0)