python - 不要等待异步函数完成

标签 python asynchronous tornado

我有一个调用异步函数的异步 Tornado 服务器。但是,该函数只是进行一些后台处理,我不想等待它完成。我怎样才能做到这一点?这是我所拥有的示例:

@gen.coroutine
def get(self):
    yield self.process('data') # I don't want to wait here
    self.write('page')

    @gen.coroutine
    def process(self, arg):
        d = yield gen.Task(self.otherFunc, arg)
        raise gen.Return(None)

最佳答案

只需删除 self.process('data') 之前的yield即可。它仍然会运行,但 get 函数不会等待它完成。示例:

@gen.coroutine
def get(self):
    print 'a'
    yield self.process('data') # I don't want to wait here
    print 'b'
    self.write('page')

@gen.coroutine
def process(self, arg):
    print 'c'
    d = yield gen.Task(self.otherFunc, arg)
    print 'd'
    raise gen.Return(None)

将给出 a、c、d、b,但是:

@gen.coroutine
def get(self):
    print 'a'
    self.process('data') # I don't want to wait here
    print 'b'
    self.write('page')

@gen.coroutine
def process(self, arg):
    print 'c'
    d = yield gen.Task(self.otherFunc, arg)
    print 'd'
    raise gen.Return(None)

可以根据订单执行给出 a,c,b,d 或 a,b,c,d,但它将不再等到流程完成才到达“b”。

关于python - 不要等待异步函数完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25083084/

相关文章:

python - Tornado eventloop 在产生多个 gen.Task 时引发 "NoneType object is not iterable"

python - 解析文本文件并对某些值进行分组

python - 在 Mac 上更新 python 版本

python - 如何切片 PandasGroupByObject 并在 agg 中使用多个函数

使用回调的 JavaScript 异步填充条

python - 为什么 'tornado.ioloop.IOLoop.instance().start()' 给我一个错误?

python - 从任何(不安全)字符串创建(正常/安全)应用程序包标识符

c# - Task.ContinueWith() 未按预期执行

javascript - 通过 ajax 调用在 componentDidMount 中正确设置测试状态

javascript - ZeroMQ 在 Web 应用程序中的使用 : how frontend interacts with backend