When you have an older javascript library that supports asynchronous calls via callbacks, you might want to wrap them in a promise instead. Particularly if you’re using Angular. For my own reference, this is how to do it. I’m using Angular’s $q, but I suspect it should be more or less the same with Q.

Let’s assume this is the method with the callbacks:

function goAsync(input, success, error) {
    try {
        // do something here
        success(result);
    } catch {
        error();
    }
}

Wrapping this in a promise is quite easy:

promiseObject.go = function(input) {
    var deferred = $q.defer();
    oldSchoolObject.goAsync(
        input,
        function(result) {
            deferred.resolve(result);
             $rootScope.$apply();
        },
        function(e) {
            deferred.reject(e);
             $rootScope.$apply();
        }
    return deferred.promise;
}

Notice how I call $rootScope.$apply after resolving or rejecting the deferred. This is so Angular starts its digest-cycle and the UI is updated.

Now you can use the promise:

promiseObject.go(input)    .then(function() {})    .catch(function() {});

You can see a live example of this in one of my GitHub repositories.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.