Posted to tcl by apn at Fri Jan 08 05:55:34 GMT 2016view raw

  1. Example session of checking urls in parallel (*async, non-blocking*) using promises:
  2.  
  3. % set urls [list http://www.google.com http://127.0.0.1:1234 http://www.yahoo.com]
  4. http://www.google.com http://127.0.0.1:1234 http://www.yahoo.com
  5. % set gate [checkurls $urls]
  6. ::oo::Obj65
  7. % $gate done puts
  8. {http://www.google.com/ ok} {http://127.0.0.1:1234/ error} {http://www.yahoo.com/ ok}
  9. % $gate destroy
  10.  
  11. And the actual promise-based code:
  12.  
  13. package require http
  14. package require lambda
  15. proc checkurl {url} {
  16. set prom [promise::Promise new]
  17. http::geturl $url -method HEAD -command [lambda {prom tok} {
  18. upvar #0 $tok url_state
  19. $prom fulfill [list $url_state(url) $url_state(status)]
  20. ::http::cleanup $tok
  21. } $prom]
  22. return $prom
  23. }
  24.  
  25. proc checkurls {urls} {
  26. return [promise::all [lmap url $urls {checkurl $url}]]
  27. }
  28.