瀏覽代碼

fix AwaitableResponse.none

Falko Schindler 1 年之前
父節點
當前提交
2167dfa0c1
共有 3 個文件被更改,包括 11 次插入13 次删除
  1. 9 11
      nicegui/awaitable_response.py
  2. 1 1
      nicegui/element.py
  3. 1 1
      nicegui/elements/scene.py

+ 9 - 11
nicegui/awaitable_response.py

@@ -1,13 +1,14 @@
 from __future__ import annotations
 
-from typing import Callable
+from asyncio import Task
+from typing import Callable, Optional
 
 from . import background_tasks
 
 
 class AwaitableResponse:
 
-    def __init__(self, fire_and_forget: Callable, wait_for_result: Callable) -> None:
+    def __init__(self, fire_and_forget: Optional[Callable], wait_for_result: Optional[Callable]) -> None:
         """Awaitable Response
 
         This class can be used to run one of two different callables, depending on whether the response is awaited or not.
@@ -15,19 +16,16 @@ class AwaitableResponse:
         :param fire_and_forget: The callable to run if the response is not awaited.
         :param wait_for_result: The callable to run if the response is awaited.
         """
+        self.fire_and_forget_task: Optional[Task] = \
+            background_tasks.create(self._start(fire_and_forget), name='fire and forget') if fire_and_forget else None
         self.wait_for_result = wait_for_result
-        self.fire_and_forget_task = background_tasks.create(self._start(fire_and_forget), name='fire and forget')
 
     async def _start(self, command: Callable) -> None:
         command()
 
     def __await__(self):
-        self.fire_and_forget_task.cancel()
+        if self.fire_and_forget_task is not None:
+            self.fire_and_forget_task.cancel()
+        if self.wait_for_result is None:
+            raise ValueError('AwaitableResponse has no result to await')
         return self.wait_for_result().__await__()
-
-    @staticmethod
-    def none() -> AwaitableResponse:
-        """Return an AwaitableResponse that does nothing."""
-        async def do_nothing():
-            return None
-        return AwaitableResponse(lambda: None, do_nothing)

+ 1 - 1
nicegui/element.py

@@ -410,7 +410,7 @@ class Element(Visibility):
         :param args: arguments to pass to the method
         """
         if not globals.loop:
-            return AwaitableResponse.none()  # TODO: raise exception instead?
+            return AwaitableResponse(None, None)  # TODO: raise exception instead?
         args_string = json.dumps(args)
         return self.client.run_javascript(f'''
               const element = getElement("{self.id}");

+ 1 - 1
nicegui/elements/scene.py

@@ -124,7 +124,7 @@ class Scene(Element,
         :param args: arguments to pass to the method
         """
         if not self.is_initialized:
-            return AwaitableResponse.none()  # TODO: raise exception instead?
+            return AwaitableResponse(None, None)  # TODO: raise exception instead?
         return super().run_method(name, *args)
 
     def _handle_click(self, e: GenericEventArguments) -> None: