await_callback

compas.utilities.await_callback(async_func, callback_name='callback', errback_name=None, *args, **kwargs)[source]

Wait for the completion of an asynchronous code that uses callbacks to signal completion.

This helper function turns an async function into a synchronous one, waiting for its completion before moving forward (without doing a busy wait).

It is useful to minimize “callback hell” when more advanced options like asyncio are not available.

Parameters
  • async_func (callable) – An asynchronous function that receives at least one callback parameter to signal completion.

  • callback_name (string, optional) – Name of the callback parameter of async_func. Default is callback.

  • errback_name (string, optional) – Name of the error handling callback parameter of async_func. Default is None.

Notes

Exceptions thrown during the async execution are handled and re-thrown as normal exceptions, even if they were raised on a different thread.

Examples

The following example shows how to await an async function (do_sync_stuff in the example), using this utility:

from compas.utilities import await_callback

def do_async_stuff(callback):
    from threading import Thread

    def runner(cb):
        print('doing async stuff')
        # ..
        cb('done')

    Thread(target=runner, args=(callback, )).start()

result = await_callback(do_async_stuff)