Golang is a concurrent programming language. It has powerful features like

GoroutinesandChannelsthat can handle asynchronous tasks very well. Also, goroutines are not OS threads, and that’s why you can spin up as many goroutines as you want without much overhead, it’s stack size starts at2KBonly. So whyasync/await? Async/Await is a nice language feature that provides a simpler interface to asynchronous programming.

How Does it Work?

Started with F## and then C#, now in Python and Javascript, async/await is an extremely popular feature of a language. It simplifies the asynchronous method execution structure and, it reads like synchronous code. So much easier to follow for developers. Let’s see a simple example in C## how async/await works

static async Task Main(string[] args)
{
    Console.WriteLine("Let's start ...");
    var done = DoneAsync();
    Console.WriteLine("Done is running ...");
    Console.WriteLine(await done);
}

static async Task<int> DoneAsync()
{
    Console.WriteLine("Warming up ...");
    await Task.Delay(3000);
    Console.WriteLine("Done ...");
    return 1;
}

We have theMainfunction that would be executed when the program is run. We haveDoneAsyncwhich is an async function. We stop the execution of the code withDelayfunction for 3 seconds. Delay is an async function itself, so we call it with await.

await only blocks the code execution within the async function

In the main function, we do not callDoneAsyncwith await. But the execution starts forDoneAsync. Only when we await it, we get the result back. The execution flow looks like this

Let's start ...
Warming up ...
Done is running ...
Done ...
1

#golang #coding #golang-tools

Async/Await in Golang: An Introductory Guide
11.90 GEEK