Skip to content

Instantly share code, notes, and snippets.

@tejasrsuthar
Forked from MichalZalecki/await-async.js
Created November 16, 2021 02:02
Show Gist options
  • Save tejasrsuthar/56de39c4bec71d4a6f70933ce314a44d to your computer and use it in GitHub Desktop.
Save tejasrsuthar/56de39c4bec71d4a6f70933ce314a44d 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