Peter Morlion logo


Wrapping an old-school callback-javascript method in a promise

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
    } catch {

Wrapping this in a promise is quite easy:

promiseObject.go = function(input) {
    var deferred = $q.defer();
        function(result) {
        function(e) {
    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 *