In programming, futures are used to describe results of asynchronous computations.
Basically, it’s a way to program with variables even if some of those variables don’t have values right now.
Hopefully an example will make this more clear.
ex1 = web_get("www.example.com/1") # takes 2.4s
ex2 = web_get("www.example.com/2") # takes 2.5s
ex3 = web_get("www.example.com/3") # takes 1.9s
print(ex1, ex2, ex3)
That means, the first line must finish before the second line can start, and so on.
This program will take 6.8 seconds (sum of each
However, if you could launch each
web_get concurrently, the whole program could take as little as 2.5s, which is the time for the slowest of the three calls.
For a fully asynchronous program, the theoretical total time is the time taken by the slowest individual part, rather than the sum of the times for all the parts.
For practical programs, futures make it somewhat easier to combine sync+async code.
In the above example, the
print function needs the results of all 3
web_get functions, so it has to wait until they’re all finished.
In Python, you could express this goal with the
ex1 = asyncio.create_task(web_get("www.example.com/1"))
ex2 = asyncio.create_task(web_get("www.example.com/2"))
ex3 = asyncio.create_task(web_get("www.example.com/3"))
print(await ex1, await ex2, await ex3)
This example looks pretty clean, although I’ve omitted the definition for
And based on the first example,
web_get must have been a normal (synchronous) function.
asyncio-enabled code therefore requires changing the definition for
web_get to make it asyncronous.
While this is a minor change, it is also a limitation, because
web_get can be synchronous or asynchronous, but it can’t be both within the same program.