23 September 2013

Using $q promises to run synchronous code asynchronously

The Q Javascript library provides a great way to handle the results of asynchronous tasks in a simple flexible manner. But the APIs required to actually generate and return promises for your own synchronous code are often a bit verbose, particularly if you want to catch and pass on exceptions as well.

Here's a convenient shortcut: Just call $q.when() with no arguments, then place all of your synchronous code (that you want to behave asynchronously) in a subsequent .then() call. This will automatically pick up any results, or exceptions, and pass them on as promises.

E.g.
function myAsyncSqrt(value) {

  return $q.when()
    .then(function() {
      return Math.sqrt(value);
    });
}
...
var promise = myAsyncSqrt(16);
promise.then(
  function(res) { alert('answer:' + res); },
  function(err) { alert('uh oh:' + err); });

No comments: