GvRs App Engine ndb Library以及monocle和 - 据我所知 - 现代Javascript使用生成器使异步代码看起来像阻塞式代码。
事物被装饰为
使用这样的函数,您会得到一个
这一切都很好,但如何添加类型注释呢?正确的类型为:
不幸的是,这不仅涉及到
事物被装饰为
@ndb.tasklet
。当它们想要将执行权交还给运行循环时,它们会yield
,当它们准备好结果时,它们会raise StopIteration(value)
(或别名ndb.Return
):@ndb.tasklet
def get_google_async():
context = ndb.get_context()
result = yield context.urlfetch("http://www.google.com/")
if result.status_code == 200:
raise ndb.Return(result.content)
raise RuntimeError
使用这样的函数,您会得到一个
ndb.Future
对象,并在其上调用get_result()
函数以等待结果并获取它。例如:def get_google():
future = get_google_async()
# do something else in real code here
return future.get_result()
这一切都很好,但如何添加类型注释呢?正确的类型为:
- get_google_async() -> ndb.Future(通过yield)
- ndb.tasklet(get_google_async) -> ndb.Future
- ndb.tasklet(get_google_async).get_result() -> str
cast
来转换异步函数的类型。def get_google():
# type: () -> str
future = get_google_async()
# do something else in real code here
return cast('str', future.get_result())
不幸的是,这不仅涉及到
urlfetch
,还涉及到数百种方法 - 主要是ndb.Model的方法。