A promise holds callbacks into asynchronous computations freeing both from concerns regarding the progress of the other. We describe a simple implementation that allows only two participants and disregards the possibility of errors.
First the promise abstraction.
createPromise = ()-> doneCallback = undefined resolution = undefined promise = whenDone: (callback)-> if doneCallback? console.log "can't whenDone me twice!" if resolution? callback(resolution) else doneCallback = callback resolve: (result)-> if resolution? console.log "can't resolve me twice!" if doneCallback? doneCallback(result) else resolution = result promise
Then a sample application.
boilWater = createPromise() pourWater = createPromise() boilWater.whenDone (result)-> delay -> pourWater.resolve( result + ' plus tea' ) pourWater.whenDone (result)-> console.log result boilWater.resolve('hot water')
This reports "hot water plus tea" for any arrangement of calls on resolve or whenDone.
We've used this promise implementation to separate meaning from infrastructure of a toy interpreter for expressions like [8, 9, 'foo', 2] where literals are to be summed sequentially and 'foo' returns 42 asynchronously.
Promises have been offered as technique to simplify the Rollup scenario from our exploration of Models for SFW.