Python's Equivalent of JavaScript Promises
Last Updated :
04 Dec, 2024
When we work with JavaScript, we often use Promises to handle asynchronous tasks. A Promise is like a promise in real life - it guarantees something will happen in the future. Python doesn't have Promises. In Python, handling asynchronous tasks is a bit different from JavaScript. We can use asyncio, await, and asyncio.gather() to manage multiple tasks. We can handle errors with try and except, just like .catch() in JavaScript Promises. If we need more control, we can even use Future objects.
Using asyncio and await in Python
In Python, asyncio module helps us deal with asynchronous programming. We use async to define a function as asynchronous and await to pause the function until the task is done.
Python
import asyncio
# Asynchronous function that simulates a task
async def task():
result = "Task Completed"
return result
# Main function to call the task and print the result
async def main():
result = await task() # Wait for the task to finish
print(result)
# Run the main function
asyncio.run(main())
Using Callbacks
A callback is a function that gets passed as an argument to another function. It will be called when that function finishes its task. This method is simple and easy to understand.
Python
# Function that does some task
def task(callback):
# Simulating some work
result = "Task Completed"
callback(result)
# Callback function that handles the result
def handle_result(result):
print(result)
# Calling the task function with the callback
task(handle_result)
Using concurrent.futures (Advanced Option)
The concurrent.futures module allows us to run tasks asynchronously using threads or processes. This is useful when we need to run several tasks at once and handle them in the background.
Python
import concurrent.futures
# Function to simulate a task
def task():
return "Task Completed"
# Using ThreadPoolExecutor to run the task asynchronously
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(task) # Submit the task
result = future.result() # Get the result once the task is done
print(result)
Using asyncio.gather()
If we have multiple asynchronous tasks and we want to wait for them to finish at the same time, asyncio.gather() is very useful. It allows us to group tasks and wait for all of them to complete.
Python
import asyncio
# Asynchronous function to simulate a task
async def task(name):
await asyncio.sleep(0.01)
return f"Task {name} Completed"
# Main function to run multiple tasks concurrently
async def main():
tasks = [task(1), task(2), task(3)]
results = await asyncio.gather(*tasks) # Run all tasks concurrently and wait for them
for result in results:
print(result)
# Run the main function
asyncio.run(main())
OutputTask 1 Completed
Task 2 Completed
Task 3 Completed