Laissez-faire
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:
-
The only way to reject a promise is with an Error instance. Even if you call reject
. This means you don't need to throw errors, you can return them with the exact same effect.
-
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.
-
Doesn't provide a separate resolver objects from the promise itself. Separation of the promise is intended to protect against assholes resolving promises they didn't make. The promise will usually be frozen too after it is fulfilled/rejected to again prevent assholes from causing trouble. Why is everyone so paranoid around promises? I left these security features out of my implementation since the cost (not just performance) benefit seemed way out of balance. As long as the 3rd party code you share your promises with isn't written by children you should sleep fine at night.
As a result of the different error handling semantics Laissez-faire fails many of the common tests found in the promises test suite written by Domenic Denicola. Though Since most people only use real Errors anyway you should be able to replace your existing promise implementation with Laissez-faire
fairly easily. It comes with a lightly modified version of the promises test suite as well as 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
- Simpler error semantics
- Easier to debug (uncaught errors are logged)
- Flexible API
What makes it worse
- Not asshole proof
API
var Promise = require('laissez-faire')
var promise = new Promise
- promise.then(done, success)
- promise.end(done, success)
- promise.later(done, success)
- promise.resolve(value)
- promise.reject(error)
- promise.assign(value|error)
Handle uncaught errors just set Promise.prepareException = function (failingPromise, error) {}
And to cancel the logic you set in motion set Promise.cancelException = function (noLongerfailingPromise) {}
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 was variables are for? Yes that is what variables are for. Except variables break if the computation occurs at any time other than right now. And now you see the problem they are designed to solve. Promises allow you to not care when the computation occurs just that it does. 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 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. 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 computations must know how to manage a promise, as 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. Lets see if we can visualize a program written synchronously and contrast it with one using promises in place of variables. Then lets look at one using callbacks. Lets perform a sequence of additions on unknown values.
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 can coding be spent optimizing algorithms.
Sync only:
var a = {},
b = 2
try {
throw new Error
} catch (e) {
c = 0
}
c += 1
console.log(c)
Note: JavaScript won't throw an error when adding an object and a number like I though when I first wrote the example so we are throwing one manually.
Timing irrelevant (with promises):
var a = new Promise().assign({}),
b = new Promise().assign(2),
c = a
.then(function(a){
return b.then(function(b) {
return new Error
})
})
.then(null, function(e) {
return 0
})
.then(function (c) {
return c + 1
})
.then(console.log.bind(console))
Here we assigned values to the promises immediately, and therefore, the subsequent computations were run immediately. However, if it took all year for their values to be computed that would be fine. The first operation actually returns a promise. This is fine since when Laissez-faire
see a promise being resolved with a promise it is smart enough to know not to take this literally and will instead fetch the value from the returned promise before resolving for real. In JavaScript the + operator returns a value instantly though the above code would work fine if it was to return a promise and take its sweet time doing the actual operation.
Timing irrelevant (with callbacks):
var c
getA(function(a){
getB(function(b){
try {
throw new Error
} catch (e) {
c = 0
}
c.plus(1, console.log.bind(console))
}))
})
Notice: that we used a plus method with a callback. Since that for this entire operation to be free from the need for instant operation every operation must be async/sync safe. It still depends on the assignment operation being done instantly however.
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 is 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.
Generators
Promises are often compared to the upcoming JavaScript feature "Generators". It is true that they are the solution to many of the same problems; however, they have very different semantics. Don't get confused by comparisons between the two like I did. Generators are probably closer to event emitters.
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.