Generators
You may have noticed that whenever we get the results/files from a task, we use an async for loop. This is because tasks can produce multiple results/files over time, and using a generator allows us to process them as they become available without waiting for all of them to be ready.
from hyperscript import Hyperscriptfrom hyperscript.convergence import Convergenceimport os
def output_multiple_results(): import time for i in range(5): # Yield results one by one. We could also yield files here if needed. yield f"Result {i}" time.sleep(1) # Simulate some delay
def multiply_by_3(value): return value * 3
async def main(): # Set up Convergence as our backend convergence = Convergence(api_key=os.getenv("CONVERGENCE_API_KEY"))
# Initialize Hyperscript with Convergence's storage and event systems async with Hyperscript( storage=convergence.storage, events=convergence.events ) as hs: # Run the hello_world function in the cloud task = await hs.run( fn=output_multiple_results, executor=convergence.executor)
tasks = []
# Now we can process results as they come in async for result in task.results(): print(f"Got result: {result}") # Should print the line count of the file # Now we can process each result further if needed processed_task = await hs.run( fn=multiply_by_3, args=[result], executor=convergence.executor) tasks.append(processed_task)
# Retrieve processed results for t in tasks: async for processed_result in t.results(): print(f"Processed result: {processed_result}")
if __name__ == "__main__": import asyncio
asyncio.run(main())