Skip to content

Instantly share code, notes, and snippets.

@mgtitimoli
Last active December 28, 2021 11:45
Show Gist options
  • Save mgtitimoli/6c8109bb45444ca66320 to your computer and use it in GitHub Desktop.
Save mgtitimoli/6c8109bb45444ca66320 to your computer and use it in GitHub Desktop.
function isPromise(thing) {
return (
typeof thing === "object" && thing !== null
&& thing.then instanceof Function
&& thing.catch instanceof Function
);
}
function whileGenerates(gen, prevGenResult) {
if (isPromise(prevGenResult.value)) {
prevGenResult.value
.then(promResult => whileGenerates(gen, gen.next(promResult)))
.catch(gen.throw.bind(gen));
}
else if (prevGenResult.value instanceof Error) {
gen.throw(prevGenResult.value);
}
else if (!prevGenResult.done) {
whileGenerates(gen, gen.next(prevGenResult.value));
}
}
function runGenerator(generator) {
"use strict";
let gen = generator();
whileGenerates(gen, gen.next());
}
// TEST
function asyncTask(timeoutMs, error, result) {
return new Promise(
(resolve, reject) => setTimeout(
() => error
? reject(error)
: resolve(result),
timeoutMs
)
);
}
runGenerator(function* () {
"use strict";
console.time("async1");
let result = yield asyncTask(3000, null, "async task #1 result");
console.timeEnd("async1");
console.log(result);
try {
console.time("async2");
result = yield asyncTask(5000, new Error("async task #1 error"));
}
catch (error) {
console.timeEnd("async2");
console.error(error);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment