Python Promises/A+ implementation

2.3.0 · active · verified Fri Apr 10

The `promise` library provides a Promises/A+ implementation for Python, designed to handle asynchronous operations with a familiar API akin to JavaScript Promises. It offers readable, performant code with essential extensions for Python development, including a `DataLoader` implementation. The library is currently at version 2.3.0 and sees occasional updates, focusing on performance, thread-safety, and compatibility.

Warnings

Install

Imports

Quickstart

Demonstrates creating a basic Promise and chaining `.then()` and `.catch()` callbacks for handling resolution and rejection.

from promise import Promise

def my_async_operation(resolve, reject):
    # Simulate an async task
    import time
    time.sleep(0.1)
    success = True # or False for rejection
    if success:
        resolve('Data fetched successfully!')
    else:
        reject('Failed to fetch data.')

# Create a promise
promise_instance = Promise(my_async_operation)

# Chain operations with .then() and handle errors with .catch()
promise_instance.then(
    lambda result: print(f'Resolved: {result}')
).catch(
    lambda error: print(f'Rejected: {error}')
)

# To make the example runnable without an explicit event loop for simple cases:
# In a real async application (e.g., with asyncio), you would integrate it with the event loop.
# This example is synchronous after the sleep, demonstrating the promise structure.

view raw JSON →