Question

I'm playing with Angular.js and especially with $http and the following code:

$http.get('test.url').onsuccess(function(res){});

I was wondering how can I program a structure like that. First try was to determine this within the Angular.js code, but my JavaScript knowledge is maybe a way too weak to understand all the code.

So, I tried the following myself:

var command = function(){
    this.execute = function(cmd){
        setInterval(function(){
            // What to call here?
        }, 60 * 60, 1000);

        return this;
    };

    this.onsuccess = function(callBack){
            return this;
    }
}

var bla = new command();

bla.execute("myCommand").onsuccess(function(result){
    console.log(result);
});

I'm pretty sure my code is wrong as hell. What have I to call to get all this stuff working?

Was it helpful?

Solution

These are promises. They're an abstraction that allows you to easily compose continuation. Here is a great read about it. This is also worth checking.

A very naive and basic way to do what you're trying here is:

var command = function(){
    var cbs = [];
    this.execute = function(cmd){
        setInterval(function(){
            cbs.forEach(function(f){ f();}); // call all callbacks
        }, 60 * 60, 1000);

        return this;
    };

    this.onsuccess = function(callBack){
         // a return this here would require a queue- and do return a different generic command
         // so we're not doing it here
         cbs.push(callBack); // add a callback to the list of handlers
    }
}

With a promise library like Bluebird - you'd do:

Promise.delay(1000).then(function(yourThing){

});

OTHER TIPS

Those fluent interfaces are different from other fluent interfaces in that each method returns a promise. jQuery has its own promise methods, but can be worked with q. Angular uses q ($q). You can also use q for asynchronous operations other than xhr requests.

Angular works with promises, but you can implement the same kind of functionality without promises:

var command = function(){
    this.execute = function(cmd){
        var theCallback;
        setInterval(function(){

            if(typeof theCallback === "function"){
                theCallback();
            }

        }, 60 * 60, 1000);

        return {
            onsuccess: function(callback){
                theCallback = callback;
            } 
        };
    };
}

var bla = new command();

bla.execute("myCommand").onsuccess(function(result){
    console.log(result);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top