Promises/A in CoffeeScript

by slace

CoffeeScript

class Promise
    notify = () ->
        if curr == status.fulfilled
            while success.length
                x = success.pop()
                x.call @res
                
        if curr == status.unfulfilled
            while failed.length
                x = failed.pop()
                x.call @res
        @

    success = []
    failed = []
    progress = []

    status =
        unfulfilled: -1,
        fulfilled: 1,
        failed: 0

    curr = status.unfulfilled
    
    constructor: (what) ->
        setTimeout ->
            try
                @res = what()
                curr = status.fulfilled
            catch e
                @res = undefined
                curr = status.unfilfulled
                
            notify()
        , 0

    then: (fulfilled, unfulfilled, inProgress) ->
        success.push fulfilled if fulfilled
        failed.push unfulfilled if unfulfilled
        progress.push inProgress if inProgress
        
        notify()
        

foo = new Promise ->
        i = 0
        stop = (new Date()).getSeconds() + 3
        while (new Date()).getSeconds() < stop
            i++
            
        i

foo.then () -> console.log this.toString()
        
setTimeout ->
    foo.then -> 
        console.log this.toString()
, 1000