3 ms·
I think promises are easy to understand. Lets start with the most basic element of a promise: the `then` method. It is so basic in fact, that the spec only cov
by lightblade 13y ago
I think promises are easy to understand.
Lets start with the most basic element of a promise: the `then` method. It is so basic in fact, that the spec only covers on how this method should behave and nothing else. All the other functions that you see in the libraries (Q, whenjs, etc) just have a lot of combinator functions that's built on top of the `then` method. Take the `Q.all` for example, it functions the same `then` except it wait for all promises passed into to it to finish before continuing with its own `then`. So understanding how the `then` behaves is essential to understanding promises.
IMO, the advantage of using promise is how composable it is. To achieve desired effect, you can take a few existing promise combinators, compose them together with just object/array literals and function calls.
For example, the other day I needed a html form to submit with a load mask covering the form while waiting for the submission to complete. The problem is that this submission can take anywhere from 21ms to 1500ms to complete. In order to achieve good UX, I needed the load mask to be not just a flash in the extremely fast case, but also not taking more than necessary time to complete in the extremely slow case. So I did this...
Q.all([ asyncFormSubmitReturnPromise(), Q.delay(500) ]).then(function() {
// hide mask & other cleanup
})
For comparison, to achieve the same effect using asyncjs...
async.parallel([
function(callback){
asyncFormSubmit({
success: callback
})
},
function(callback){
setTimeout(callback, 500)
}
],
function(err, results){
// hide mask and cleanup
})
I want to mention another advantage with promises: it creates an uniformed interface that disregards whether the loading is synchronous or asynchronous. Say for example you're writing a select box widget that needs to populate the dropdown's content. Your widget can expose a method just called `load` and it takes a promise. Now whoever is calling your `load` method will have the total freedom to pass in a promise's already resolved or pending to be resolved. If you have the data at hand, it's just as easy to wrap it in a promise `Q.resolve(data)` and pass it in.