Chapter 3. Writing Asynchronous Code with Deferreds
Callbacks are a fundamental part of event-driven programming and are the way that the reactor indicates to an application that an event has arrived. As event-driven programs grow, handling both the success and error cases for the events in one’s application becomes increasingly complex. Failing to register an appropriate callback can leave a program blocking on event processing that will never happen, and errors might have to propagate up a chain of callbacks from the networking stack through the layers of an application.
Twisted provides an elegant abstraction called a Deferred
to manage these callbacks. This chapter
will give you practice using Deferred
s by
themselves and then demonstrate their real-world utility by integrating
Deferred
s into some client and server examples.
We’ll use Deferred
s while writing
asynchronous servers and clients throughout the remainder of this
book.
What Deferreds Do and Don’t Do
It’s worth heading off a common misconception up front:
Deferred
s do help you write asynchronous code.Deferred
s do not automatically make code asynchronous or nonblocking. To turn a synchronous function into an asynchronous function, it’ll need to be refactored to return aDeferred
with which callbacks are registered.
Practice will help you develop an intuition for how to structure
asynchronous code. Let’s look at a Deferred
so you can start getting some of that
practice.
The Structure of a Deferred Object
Deferred
s have a pair ...
Get Twisted Network Programming Essentials, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.