0

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?

  • 1
    These are promises. They're an abstraction that allows you to easily compose continuation. Here is [a great read](http://modernjavascript.blogspot.co.il/2013/08/promisesa-understanding-by-doing.html) about it. [This is also worth checking](http://spion.github.io/posts/why-i-am-switching-to-promises.html). – Benjamin Gruenbaum Feb 08 '14 at 14:30

3 Answers3

0

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.

Josh C.
  • 4,303
  • 5
  • 30
  • 51
0

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){

});
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
0

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);
});
Kenneth
  • 28,294
  • 6
  • 61
  • 84