官术网_书友最值得收藏!

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
主站蜘蛛池模板: 内江市| 荥阳市| 盈江县| 满城县| 岚皋县| 东宁县| 息烽县| 玉山县| 旅游| 城固县| 乐昌市| 新疆| 麻阳| 晴隆县| 冀州市| 嵩明县| 北安市| 长沙市| 柏乡县| 无为县| 营山县| 房产| 社旗县| 富顺县| 金昌市| 林周县| 邻水| 防城港市| 尖扎县| 登封市| 乡城县| 双桥区| 高雄市| 临西县| 木里| 景泰县| 图木舒克市| 阜平县| 萨迦县| 平湖市| 长岭县|