-
Notifications
You must be signed in to change notification settings - Fork 2
How `async` works
Computer programs work in a sequential order. If you have code like this:
function1()
function2()
function3()
Then function1()
will run first, then function2()
, and finally function3()
. This is what is known as synchronous programming - one thing comes after another, in sync. You can think of it in terms of a factory line like this, where each instruction is followed step-by-step:
function1()
|
v
function2()
|
v
function3()
When we try to do things like accessing APIs, these functions can often be slow:
function1()
api()
function2()
In the above code, api()
might take a long time. This means that function2()
takes a long time to execute, simply because it's after api()
. This causes the iOS app to freeze, which is not a good thing and can lead to lagging and crashes.
Enter async
and await
: two keywords from AwaitKit
that allow you to access API functions, but don't cause the app to crash! What these new keywords allow you to do is they allow you to write code on a separate thread, which can be thought of as a separate factory line.
Main line Async line
function1()
|
v
async -----> function2()
| |
v v
function4() function3()
This is known as asynchronous programming - moving stuff between these threads so that multiple bits of code can run at the same time without affecting one another.
You can write code like this:
function1()
function2()
async {
try await(api())
try await(api2())
functionThatDependsOnAPI()
}
What async
does is it creates a separate thread where all of the API code, which could freeze up the app, is run separately from everything else. await
basically says "wait until this bit of code is finished before running everything else". await
can only be used on asynchronous functions, like API requests in the app.