python - twisted ordered DeferredList -


is possible create deferredlist (or similar) runs deferred in defined order ?

i need run list of deferred, ideally deferred should wait on previous one, can alter next deferred result:

#!/usr/bin/env python # -*- coding: utf-8 -*-  """  """  __future__ import division, absolute_import, \     print_function, unicode_literals  twisted.internet import defer, reactor   def multiply(n):     if n == 3:         import time         time.sleep(1)     print(n * 10)     return n * 10   def stopifresultisabove20(n):     if n > 20:         print('result above 20, stop following deferreds')         raise exception('the result above 20, cancelling other deferreds')     return n   def onsuccess(result):     print(result)     return result   def onerror(failure):     print('failed !')     pass  requests = [] n in range(0, 6):     d = defer.deferred()     d.addcallback(multiply)     d.addcallback(stopifresultisabove20)     if n == 3:         twisted.internet import threads         threads.defertothread(d.callback, n)     else:         reactor.calllater(0, d.callback, n)     requests.append(d)  dl = defer.deferredlist(requests,                         fireononeerrback=true) dl.addcallbacks(onsuccess, onerror) dl.addboth(lambda _: reactor.stop())  reactor.run() 

what do:

  • create multiple deferreds
  • each following deferred wait on previous one
  • if previous 1 had result > 20, stop chain

edit: can achieve @inlinecallback decorator , make code synchronous, i've read @inlinecallbacks should avoided, i'd achieve traditional deferred code

there's nothing wrong @inlinecallbacks. reason you've been told avoid @inlinecallbacks it's far easy make code accidentally sequential this; when you're using deferreds want parallelism, , it's hard notice you've given if code looks blocking. however, if understand how works, @inlinecallbacks fine whenever want use it; , if want sequential behavior this, @inlinecallbacks perfect.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -