Last active
February 1, 2016 02:41
-
-
Save shinux/1c8128e53d0fa5ba9236 to your computer and use it in GitHub Desktop.
Synchronous proxy
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
/** | |
* | |
* 异步 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