Last active
November 26, 2015 08:48
-
-
Save lbarasti/a538258f438798ed1fa5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class P | |
| notify = (d, value) -> | |
| P.run -> d.fulfil(d.onFulfil?(value)) | |
| fulfil: (value) -> | |
| @value = value | |
| @dependencies.forEach (d) -> | |
| notify(d, value) | |
| return this | |
| then: (d) -> | |
| wrapped = new P(d) | |
| if @value? then notify(wrapped, @value) | |
| else @dependencies = @dependencies.concat(wrapped) | |
| return wrapped | |
| constructor: (@onFulfil) -> | |
| @dependencies = [] | |
| @combine: (args...) -> | |
| remaining = args.length | |
| waiting = new P | |
| args.forEach (promise) -> promise.then(-> | |
| remaining = remaining - 1 | |
| if remaining == 0 | |
| waiting.fulfil(args.map((p) -> p.value)) | |
| ) | |
| return waiting | |
| @run: (f) -> setTimeout f, 0 | |
| count_to = (n) -> | |
| while n > 0 | |
| n = n - 1 | |
| a = new P() | |
| b = a.then (v) -> console.log('b'); v + 1 | |
| c = b.then (v) -> console.log('c'); count_to 100000; v ** 2 | |
| d = P.combine(a,b,c).then((args) -> console.log 'd'; args) | |
| logStatus = -> console.log [a, b, c, d].map((v) -> v.value) | |
| logStatus() | |
| a.fulfil (-> console.log 'a'; 5)() | |
| setTimeout (-> | |
| count_to 10000000; | |
| setTimeout(logStatus, 0) | |
| setTimeout(logStatus, 1000) | |
| logStatus()), 0 | |
| logStatus() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment