Skip to content

Instantly share code, notes, and snippets.

@MelkorNemesis
Last active May 10, 2022 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MelkorNemesis/051204e3a582987870f00fd0ebad37c7 to your computer and use it in GitHub Desktop.
Save MelkorNemesis/051204e3a582987870f00fd0ebad37c7 to your computer and use it in GitHub Desktop.
import fetch from "isomorphic-fetch";
function getUser(userId) {
return fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
.then((res) => {
if (!res.ok) {
throw new Error(res.statusText);
}
return res;
})
.then((res) => res.json());
}
function throwError() {
return Promise.reject(new Error("Oops"));
}
// ----- Async/await version
async function main() {
const user1 = await getUser(1);
const user2 = await getUser(2);
// const user2 = await throwError();
const user3 = await { name: "John Lewis" };
return user1.name + ", " + user2.name + ", " + user3.name;
}
const resultAsync = main();
resultAsync
.then(console.log)
.catch((err) => console.log("Error from async", err));
// ----- Coroutine
function co(genFn, ...args) {
const it = genFn(...args);
function handleIteratorResult({ value, done }) {
if (done) {
return Promise.resolve(value);
}
if (value && value.then) {
return value
.then((val) => handleIteratorResult(it.next(val)))
.catch((err) => handleIteratorResult(it.throw(err)));
} else {
return Promise.resolve(it.next(value)).then(handleIteratorResult);
}
}
return handleIteratorResult(it.next());
}
// ----- Generator version
function* mainGen(val) {
console.log(val);
const user1 = yield getUser(1);
const user2 = yield getUser(1);
// const user2 = yield throwError(2);
const user3 = yield { name: "John Lewis" };
return user1.name + ", " + user2.name + ", " + user3.name;
}
const resultGenerator = co(mainGen, 42);
resultGenerator
.then(console.log)
.catch((err) => console.log("Error from generator", err));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment