Last active
December 16, 2015 11:08
-
-
Save jineeshjohn/5424891 to your computer and use it in GitHub Desktop.
A sample to test the promise pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
1) doing things in sequence | |
$(btn).click(function(){ | |
getTwitterHandle(function(){ | |
getTweets(function(){ | |
}); | |
}); | |
}); | |
2) Doing it in parallel | |
var tweets, answers; | |
getTweets(function(result){ | |
tweets = result; | |
}); | |
getAnswers(function(result){ | |
answers = result; | |
}); | |
3) Keep track of errors using counters is even worse | |
**/ | |
function $P(p){ | |
if (p instanceof $P) { | |
return p; | |
}else{ | |
this.cbs = []; | |
} | |
} | |
$P.prototype.then = function(k,param) { | |
this.cbs.push({ok: k,args:param }); | |
return this; | |
}; | |
$P.prototype.resolve = function(){ | |
var cbArr = this.cbs; | |
for(var i=0; i<cbArr.length; i++){ | |
var cb = cbArr[i]; | |
cb.ok.call(this, cb.args); | |
} | |
}; | |
function testPromise(){ | |
var p = new $P(); | |
setTimeout(function(){ | |
p.resolve(); | |
},5000); | |
return p; | |
} | |
function test1(args){ | |
console.log("test1:"+args); | |
} | |
function test2(args){ | |
console.log("test2:"+args); | |
} | |
function test3(args){ | |
console.log("test3:"+args); | |
} | |
var op1 = testPromise(); | |
op1.then(test1,11).then(test2,12).then(test3,13); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment