Skip to content

Instantly share code, notes, and snippets.

@kaid
Last active September 11, 2015 06:51
Show Gist options
  • Save kaid/9a3119a96e1c4666bed5 to your computer and use it in GitHub Desktop.
Save kaid/9a3119a96e1c4666bed5 to your computer and use it in GitHub Desktop.
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