Laissez-faire
Its a promise class.
It works in node and the browser. Anything in the name? Yea its a French word meaning "let it be". Seemed apt for a library designed to eliminate the need to worry about when computation occurs.
Differences from other libraries
Laissez-faire is compliant with the Promises/A spec as far as I understand it. However, it does break from some patterns which are common in other implementations:
-
Doesn't guarantee async calls to then
; you use promises to abstract away the effects of time. Therefore, there shouldn't be any need to guarantee anything about when promises will be fulfilled. The reasoning behind this feature is usually that it makes promises easier to understand for beginners. I think its more like this feature makes it easier for users to misunderstand promises and treat them like a less ugly version of the callback pattern found in Node.
-
Paranoia is optional; a goblin proof proxy object is not created when you create a new instance of laissez. If you want to be able to pass out access to your promises value without allowing them to also assign a value to your promise you call promise.proxy()
A new proxy is generated with each call so you can pass out as many as you like.
-
API:
-
new Laissez
instead of lib.defer()
-
deferred.proxy()
instead of deferred.promise
The test suit is comprised mainly of the promises test suite written by Domenic Denicola. I leave out the always-async test since I disagree with the concept. I have added a few extra suites for Laissez-faire specific features.
Performance
Good it seems.
====================================
Test: defer-create x 10000
------------------------------------
Name Time ms Avg ms Diff %
laissez 1 0.0001 -
when 19 0.0019 1800.00
rsvp 35 0.0035 3400.00
deferred 40 0.0040 3900.00
q 453 0.0453 45200.00
====================================
Test: promise-fulfill x 10000
------------------------------------
Name Time ms Avg ms Diff %
laissez 7 0.0007 -
when 9 0.0009 28.57
deferred 12 0.0012 71.43
rsvp 86 0.0086 1128.57
q 215 0.0215 2971.43
====================================
Test: promise-reject x 10000
------------------------------------
Name Time ms Avg ms Diff %
laissez 13 0.0013 -
when 67 0.0067 415.38
rsvp 138 0.0138 961.54
deferred 162 0.0162 1146.15
q 279 0.0279 2046.15
====================================
Test: promise-sequence x 10000
------------------------------------
Name Time ms Avg ms Diff %
laissez 15 0.0015 -
deferred 38 0.0038 153.33
when 41 0.0041 173.33
rsvp 222 0.0222 1380.00
q 4634 0.4634 30793.33
What makes it better
- Smaller
- Faster
- Easier to debug (uncaught errors are logged)
- Flexible API
What makes it worse
- I haven't got around to doing any interope testing so will most likely have some bugs if you are passing it promises from other libraries.
API
var Promise = require('laissez-faire')
var promise = new Promise
- promise.then(done, success)
- promise.end(done, success)
- promise.resolve(value)
- promise.reject(error)
- promise.assign(value|error)
- promise.fail(value)
- promise.success(value)
- promise.proxy()
To handle uncaught errors just set Promise.prepareException = function (failingPromise, error) {}
And a cenceler Promise.cancelException = function (noLongerfailingPromise) {}
. In case an exception handler gets added after prepareException
was called
Basic Usage
var promise = new Promise();
promise.then(function(value) {
}, function(value) {
});
promise.resolve(value)
promise.reject(error)
Once a promise has been resolved or rejected, it cannot be resolved or
rejected again.
Here is an example of a simple XHR2 wrapper written using Laissez-faire:
var getJSON = function(url) {
var promise = new Promise()
var client = new XMLHttpRequest()
client.open("GET", url)
client.onreadystatechange = handler
client.responseType = "json"
client.setRequestHeader("Accept", "application/json")
client.send()
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) promise.resolve(this.response)
else promise.reject(this)
}
};
return promise;
};
getJSON("/posts.json").then(function(json) {
}, function(error) {
});
Understanding promises
I struggled to understand promises and that is why I started playing with this project. It would be rude of me not to share my learnings. I hope my explanation prevents you from needing to take the same route in order to understand them. Every explanation I have read begins like this: "A promise represents the eventual value returned from the single completion of an operation". I have read a few and they all sounded suspiciously wrote. That one was from the Promises/A spec. Its a shame they all choose to use the word "eventual" since it is actually slightly misleading. Promises may be resolved now. Therefore, a simpler and more accurate way of introducing promises would be to say "A promise represents the value of a computation".
This of course would raise the question: isn't that what variables are for? Yes. Except variables break if the computation occurs at any time other than right now. The problem promises are designed to solve is uncertainty due to the timing of processes. Promises take the worry away. They add some messy syntax but allow you to focus on the process which will ultimatly makes things easier to reason about. In order to do this they need to do two things.
- Store the result of the computation as soon as it happens
- Provide a mechanism to connect further computations which depend on this value
By providing these capabilities they allow you to ignore the timing of computation completely. They could easily become a language feature complimenting the less powerful variable.
You saw promises in use in the previous section but lets walk through how they are used since they look nothing like variables syntactically. First we create the promise: var promise = new Promise
. So we need to use a variable in order to use a promise. You could say then that we are creating an enhanced variable or more simply a container. Then we do some computation and assign our value to the promise return promise.assign('some value')
. Note you must always return
the promise now though you don't have to assign to it until you are good and ready. So your functions must know how to manage a promise, its a shame since semantically they aren't much different from variables, though blame that one on the language designers. Maybe one day JavaScript will be inspired and adopt message passing like Io and Smalltalk, maybe.
In summary promises are a way of storing and accessing values devoid of when. That makes them very useful for situations where you can't be certain something is going to be sitting in memory ready to go but would like to take advantage of the speed if it is. Callbacks enable this and will always be faster, however promises provide the value and error propagation infrastructure to make these programs easier to reason about. Plus implementations like Laissez-faire are actually fairly light weight so offer good bang for your buck. The time they save you coding can be spent sleeping at night.
Chaining
If you return a regular value, it will be passed, as is, to the next
handler.
getJSON("/posts.json")
.then(function(json) {
return json.post
})
.then(function(post) {
});
Returned promises are recognized as promises and have their resolved value used to resolve the promise they were returned to
getJSON("/post/1.json")
.then(function(post) {
return getJSON(post.commentURL)
})
.then(function(comments) {
})
Error Handling
Errors also propagate:
getJSON("/badurl.json")
.then(function(posts) {
})
.then(null, function(error) {
})
Technically a promise can never throw an error since at any time in the future a user could add a child promise and handle the exception. However in practice the promise user will bind their error handlers immediately, so in most cases unhandled rejections which sit around for more than one tick of the event loop are genuine errors. Laissez-faire provides a mechanism for you to hook into these errors. See the source for details. It actually uses this mechanism itself to provide a nice default behavior which is to log the errors to the console after a 1 second delay. If this doesn't suit you then it is easy to override the behavior.
Finishing with a promise
Promises represent values. Like any other value you can never be sure it will never be used again until nobody has access to it. If however you have a promise and you know the next operation you do one it will be your last there is no need to create a chainable promise from it. To allow you to reduce the cost this operation (by a little) Laissez-faire provides an end
method. It will provide the promises value to your callbacks as usual but will not return a new promise. Thereby, saving some computation. We also take advantage of the situation and allow any uncaught errors to blow up since we know you have no plans of catching them. Furthermore, end
will return this
thereby allowing a jquery style use of promises which is nice where appropriate.
var p = new Promise().assign(1)
.end(function(val){
return val + 1
})
.end(function(val){
return val + 1
})
.end(function(val){
throw new Error
})
.then(function(val){
return val + 1
}, function(){
})
.then(function(val){
console.log(val)
})
I'd be surprised if that code sample conjured the picture in your head I wanted so hear is a diagram illustrating the structure of the process.
![process](https://docs.google.com/drawings/pub?id=1MiWhL77a7X457fWy529--ic-pKI9AG1WCmY_pZdENVg&w=960&h=720)
Each box represents a process of some kind. The circles below some of the processes represent the values they expose. The first box creates the promise and exposes itself for binding. The three calls to end
each create a process but don't create new promises. Therefore, any values they might generate are lost. The fourth call, to then
, does the same thing as the others except it exposes a value to the outside world. This value is represented by a promise, therefore to access it we must use either then
or end
. In this case we used then
which resulting in the final value being exposed. This final value is 2. The flow of data is represented by the arrows with the red boxes showing the value of the data. Hopefully this illustration makes it obvious what is happing when you access the value of a promise via then
or end
, you are creating a branch in the process. Values flow down these branches in the same way as errors. Though they are of course handled by separate functions. Because we chose to use then
as the final call on the fourth branch we will be able to continue processing at any time where we left of. Be that with an error or a value, no matter, so long as the p
variable doesn't go out of scope.
In summary then we can say promises provide a mechanism to freeze process. Ready to defrost and continue via then
and end
as soon or as long as you like.
Mutability
Its widely considered that promises should be immutable and I agree. I though its interesting to note what happens to promises when they are implemented in a mutable way. So when a promise has its value changed it propagates this value to any child promises. At which point you would of switched to the Reactive programming paradigm. The change in implementation to create this effect is trivial. I guess we can say then that promises borderline bring a new paradigm to JavaScript. Its amazing how flexible this language is.