Async/Await is part of the new concurrency system. WWDC comes with new features Async/Await is one of them. Async function allows us to run complex code asynchronously.
Why do we need Async/Await function?
Commonly, we use a completion handler to handle the result, when we are making requests to fetch or push data.
For example, if one request needs to make after another one is completed. we need to put the second request in the completion handler of the first request.
1 2 3 4 5 6 |
func testfunction(completion: @escaping() -> Void) { ....... testfunction1 { ....... } } |
What if we have multiple requests to execute in a specific order?
We end up something like this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
func testfuction(completion: @escaping() -> Void) { // ... testfunction1{ // ... testfunction2{ // ... testfunction3 { // ... testfunction4 { completion() } // ... } // ... } // ... } // ... } |
There is nothing wrong with the code, it’s just a little bit complex to write and understand.
That’s why we need Async/Await function
Asynchronous Functions
To create an async function we need to add the async keyword after the parameters:
1 2 3 |
func asyncfunction() async { ........ } |
To call the async function we need to add await keyword at the front of the request to execute the request in a specific order.
1 |
await asyncfunction() |
await keyword work only if the calling function should be an asynchronous function
1 2 3 4 5 6 7 |
func asyncfunction() async { await asyncfunction1() await asyncfunction2() await asyncfunction3() } |
1 2 3 4 5 6 7 8 9 10 |
func asyncfunction1() async { ........ } func asyncfunction2() async { ......... } func asyncfunction3() async { ......... } |
Above all, functions will be executed after the previous functions are completed with the await keyword.
In conclusion, async function working is similar to the completion handler, but many times completion handler make our code difficult to understand, on the other hand, asynchronous functions clean up code and makes it more readable
I hope this blog helps you to understand the basics of an asynchronous function.
Lastly, Please share your thoughts with us in the comment section.
For more blogs please click here