In my current project, we use JavaScript promises all over the place. We use built-in angular.js $q service on the client and the great bluebird node.js promises library on the server. In fact, we don't even have any callbacks, all the "standard" node.js APIs are always "promisified".
The virtues of promises have been extolled by many people. I personally like this article a lot: https://blog.jcoglan.com/2013/03/30/callbacks-are-imperative-promises-are-functional-nodes-biggest-missed-opportunity/. I especially like the part, which tells about how promises allow "programming with values" in asynchronous contexts.
Recently I've found a very interesting use case of this "programming with values" concept. Imagine, you have a service, which returns a value (a promise of value, to be more precise), by making an HTTP request. Then you decide you want to cache this value and make sure that many requests to this method don't make extra HTTP requests before original HTTP request returned the value. That is, you need to return a cached value, which you haven't cached yet.
Doing this with promises is so simple and elegant, you just cache the original HTTP promise and return it, you don't need to check if the value has been returned (promise resolved)!
This is an excerpt of actual angular.js service (in TypeScript):
The virtues of promises have been extolled by many people. I personally like this article a lot: https://blog.jcoglan.com/2013/03/30/callbacks-are-imperative-promises-are-functional-nodes-biggest-missed-opportunity/. I especially like the part, which tells about how promises allow "programming with values" in asynchronous contexts.
Recently I've found a very interesting use case of this "programming with values" concept. Imagine, you have a service, which returns a value (a promise of value, to be more precise), by making an HTTP request. Then you decide you want to cache this value and make sure that many requests to this method don't make extra HTTP requests before original HTTP request returned the value. That is, you need to return a cached value, which you haven't cached yet.
Doing this with promises is so simple and elegant, you just cache the original HTTP promise and return it, you don't need to check if the value has been returned (promise resolved)!
This is an excerpt of actual angular.js service (in TypeScript):
Comments