Chapter 3. Asynchronous Programming
To learn what asynchronous code is, let's first cover what synchronous code is. With synchronous code, you have one statement being executed after another. The code is predictable; you know what happens and when. This is because you can read the code from top to bottom like this:
print('a')
print('b')
print('c')
// output
a, b, c
Now, with asynchronous code you lose all the nice predictability that the synchronous code offers. In fact, there is very little you know about asynchronous code other than that it finishes executing, eventually. So asynchronous, or async, code looks more like this:
asyncPrint('a')
asyncPrint('b')
asyncPrint('c')
// output
c, b, a
As you can see, the order in which a statement finishes is not determined by when a statement occurs in the code. Instead, there is a time element involved that decides when a statement has run its course.
Asynchronous code runs in an event loop. This means that async code runs in the following order:
- Run...