Skip to content

Instantly share code, notes, and snippets.

@MichalZalecki
Created November 13, 2015 05:16
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save MichalZalecki/2d9a9a1ee2afc44d6cb8 to your computer and use it in GitHub Desktop.
Save MichalZalecki/2d9a9a1ee2afc44d6cb8 to your computer and use it in GitHub Desktop.
Run generators and and await/async
import axios from "axios";
export default async function () {
const { data: { id } } = await axios.get("//localhost:3000/id");
const { data: { group } } = await axios.get("//localhost:3000/group");
const { data: { name } } = await axios.get(`//localhost:3000/${group}/${id}`);
console.log(name); // Michał
}
import axios from "axios";
run(function*() {
const { data: { id } } = yield axios.get("//localhost:3000/id");
const { data: { group } } = yield axios.get("//localhost:3000/group");
const { data: { name } } = yield axios.get(`//localhost:3000/${group}/${id}`);
console.log(name); // Michał
});
run(function*() {
try {
const { data: { id } } = yield axios.get("//localhost:3000/id");
const { data: { group } } = yield axios.get("//localhost:3000/404");
const { data: { name } } = yield axios.get(`//localhost:3000/${group}/${id}`);
console.log(name);
} catch(e) {
console.warn(e); // { status: 404, statusText: "Not Found" }
}
});
run(function*() {
const [ { data: { id } }, { data: { group } } ] = yield Promise.all([
axios.get("//localhost:3000/id"),
axios.get("//localhost:3000/group")
]);
const { data: { name } } = yield axios.get(`//localhost:3000/${group}/${id}`);
console.log(name); // Michał
});
function run(g) {
const it = g();
(function _iterate(res) {
!res.done && res.value
.then(data => _iterate(it.next(data)))
.catch(data => it.throw(data));
})(it.next());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment