<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def future_then_immediate(future, func):
 """Returns a future that maps the result of `future` by `func`. If `future` succeeds, sets the result of the returned future to `func(future.result())`. If `future` fails or `func` raises an exception, the exception is stored in the returned future. If `future` has not yet finished, `func` is invoked by the same thread that finishes it. Otherwise, it is invoked immediately in the same thread that calls `future_then_immediate`. """

    result = concurrent.futures.Future()

    def on_done(f):
        try:
            result.set_result(func(f.result()))
        except Exception as e:
            result.set_exception(e)

    future.add_done_callback(on_done)
    return result