DEV Community

Cover image for What I've learned today - 5 - Using Golang channels as async await
Luan Gomes
Luan Gomes

Posted on

6

What I've learned today - 5 - Using Golang channels as async await

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))
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode

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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up