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:

  1. Run async code
  2. Wait for the response to be ready, then fire an interrupt
  3. Run the event handler

An important thing to stress here is that async code is non-blocking—other operations can take place while async code is running. Therefore, async code is a good candidate to be used when dealing with I/O, long-running tasks, and network requests.

In this chapter, we will:

  • Learn what asynchronous programming is and how it differs from synchronous programming
  • Explain the callback model
  • Describe promises and how they completely reformed how we write asynchronous code
  • Look at which other asynchronous libraries exist and in what cases they should be used
  • Discover the new standard async/await
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.147.160