Last active
September 11, 2015 06:51
-
-
Save kaid/9a3119a96e1c4666bed5 to your computer and use it in GitHub Desktop.
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
function asyncPrefix() { | |
const prefix = "Your IP is:"; | |
return new Promise(function(resolve, reject) { | |
try { | |
let timer; | |
timer = setTimeout(function () { | |
resolve(prefix); | |
clearTimeout(timer); | |
}, 4000); | |
} catch(error) { | |
reject(error); | |
} | |
}); | |
} | |
function fetchIp() { | |
return fetch("https://api.ipify.org/?format=json") | |
.then(res => res.json()) | |
.then(json => json.ip); | |
} | |
function genRunner(gen, value) { | |
const item = value ? gen.next(value) : gen.next(); | |
if (item.done) return; | |
if (!item.value) return genRunner(gen); | |
if (typeof item.value.then === "function") { | |
item.value.then(value => genRunner(gen, value)); | |
} else { | |
genRunner(gen, item.value); | |
} | |
} | |
function asyncToSync(genMaker) { | |
genRunner(genMaker()); | |
} | |
asyncToSync(function* () { | |
const prefix = yield asyncPrefix(); | |
const ip = yield fetchIp(); | |
console.log(`${prefix} ${ip}`) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment