Future and promise
medium 50 minA future is a placeholder for a result that comes later, a promise is the one right to put it there.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Who holds the future, who settles it, and what runs when.
Operations
Coffee shop
Order 42 from submit to the first sip.
Step 1 of 8
Place the order
The caller asks the pool and does not wait for coffee.
Step 1: Place the order
def order(drink): promise = Promise() pool.execute(lambda: promise.complete(make(drink))) return promise.futureticket = order("latte")ticket.done()read_a_book()coffee = ticket.get(timeout=300)- Watch
- state
- Result
- The customer never waits
done() looks, get() waits. Here get comes when the value is there.
In the real world
The same future and promise doing real jobs. Pick one and step through it.
Two workers, two tasks, each waits for a task in the queue.
Step 1 of 3
Two outer tasks
Both workers are busy.
Step 1: Two outer tasks
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Waiting one after the other
majorIndependent calls take the sum instead of the longest.
Wronga = await fetch_a()b = await fetch_b()Righta, b = await asyncio.gather(fetch_a(), fetch_b())get inside the pool
criticalThe worker waits for a task that needs a worker.
Wrongdef outer(): return pool.submit(inner).result()Rightreturn then_compose(start_inner(), finish)# or: a second pool for inner tasksCallbacks under the lock
criticalUnknown code may call back or wait.
Wrongwith lock: self.value = v for call in self.later: call(v)Rightwith lock: self.value = v later, self.later = self.later, []for call in later: call(v)Testing the value
critical0, empty text and None are results too.
Wrongif self.result: callback(self.result)Rightif self.state != "pending": callback(self.value)Recovering on the side
majorThe default is in a new future that nobody reads.
Wrongf = fetch()recover(f, lambda e: "default")f.get()Rightf = recover(fetch(), lambda e: "default")f.get()An error that nobody reads
criticalThe task failed, the program says done.
Wrongpool.submit(save, row)print("done")Rightjob = pool.submit(save, row)job.result() # or log it in a callback
Interview tips
Two sides
- Keep the promise.
- Give away the future.
- Settle once.
Compose
- Start first, wait later.
- Value: then. Future: compose.
- One handler at the end.
Threads
- Know where callbacks run.
- Never block in the pool.
- Complete after the lock.
Every promise ends
- With a deadline.
- On a closed connection.
- Also when you drop it.
In depth
- Token for the work.
- One load per key.
- Tasks belong to a block.