Skip to content

Instantly share code, notes, and snippets.

Created December 24, 2012 07:49
Show Gist options
  • Save anonymous/4368262 to your computer and use it in GitHub Desktop.
Save anonymous/4368262 to your computer and use it in GitHub Desktop.
API内部有两个http接口A,B并发调用,如果都在200ms内返回,则合并结果输出,如果B比A慢,且B耗时超过200ms,则丢弃B调用只返回A结果.
function apiMergeCall(apis, mainid, timeout, callback){
var api_count = apis.length, ready_count = 0, rst = {}, is_ret = false, start_time = new Date().getTime(),
doCallback = function(){
if (!is_ret && (is_ret = true)) {
timer && clearTimeout(timer);
callback(rst);
}
},
chkResult = function(id, ret){
rst[id] = ret;
if (++ready_count == api_count || (id == mainid && (new Date().getTime() - start_time > timeout))) {
doCallback();
}
},
timer = setTimeout(function(){
timer = null;
(rst[mainid] !== undefined) && doCallback();
}, timeout);
apis.forEach(function(api){
api.exec(chkResult);
});
}
function Api(id, data){
this.id = id;
this.data = data;
}
Api.prototype = {
exec : function(fn){
var sleep_time = Math.round(Math.random()*300);
console.log(this.id + ' ' + sleep_time);
setTimeout(fn, sleep_time, this.id, this.data);
}
}
apiMergeCall([new Api('a', 'this is a'), new Api('b', 'this is b')], 'a', 200, function(rst){console.log(rst);});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment