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?
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){
});