On today's Smalltalk Daily, we take another look at class promise - but at the kind of usage that would be more common. Say you had a set of tasks (like, say, a bunch of HTTP downloads) that had to hapen before the next action could take place. Well, that's what class Promise is for. Here's the example code from today's Screencast:
"collection of urls"
urls := #('http://www.yahoo.com' 'http://www.cincomsmalltalk.com' 'http://www.cincomsmalltalk.com/blog/blogView' 'http://www.podcastalley.com' 'http://www.cincom.com' 'http://www.smalltalkindustrycouncil.org' 'http://www.stic.st' 'http://www.cincomsmalltalk.com/CincomSmalltalkWiki').
"block to download each one"
downloadBlock := [:url | | client response |
client := HttpClient new.
response := client get: url.
Transcript show: 'Downloaded: ', url; cr].
"with Promise"
downloads := urls collect: [:each | [downloadBlock value: each] promise].
downloads do: [:each | each value].
"without Promise"
downloads := urls collect: [:each | | sem |
sem := Semaphore new.
[downloadBlock value: each.
sem signal] fork.
sem].
downloads do: [:each | each wait].
Technorati Tags:
smalltalk