Skip to content

Instantly share code, notes, and snippets.

@shinux
Last active February 1, 2016 02:41
Show Gist options
  • Save shinux/1c8128e53d0fa5ba9236 to your computer and use it in GitHub Desktop.
Save shinux/1c8128e53d0fa5ba9236 to your computer and use it in GitHub Desktop.
Synchronous proxy
/**
*
* 异步 get 需要回调
**/
let choice = 'a';
let proxyList = [];
function initProxyWayA() {
// if proxyList comes from request.getAsync. things will get bad.
proxyList = [
{ address: 'http://192.168.0.1',
valid: true },
{ address: 'http://192.168.0.1',
valid: true },
{ address: 'http://192.168.0.1',
valid: true },
];
}
function initProxyWayB() {
proxyList = [
{ address: 'http://127.0.0.1',
valid: true },
{ address: 'http://127.0.0.2',
valid: true },
{ address: 'http://127.0.0.3',
valid: true },
];
}
// 两种方式的选择
function initialProxy() {
if (choice === 'a') {
initProxyWayA();
} else {
initProxyWayB();
}
}
// 可用性的检测
function findValidProxyIndex() {
return proxyList.findIndex((proxy) => proxy.valid);
}
function getSingleProxy() {
const idx = findValidProxyIndex();
if (proxyList.length === 0 || idx === -1) {
initialProxy();
return proxyList[0].address;
} else {
return proxyList[idx].address;
}
}
console.log(getSingleProxy());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment