Skip to content

Instantly share code, notes, and snippets.

@alpox
Created February 27, 2022 21:42
Show Gist options
  • Save alpox/a04744029bab0bf6a78b81ff0b1dbe28 to your computer and use it in GitHub Desktop.
Save alpox/a04744029bab0bf6a78b81ff0b1dbe28 to your computer and use it in GitHub Desktop.
Async await
const asyncFun = fun => (...args) => {
const gen = fun(...args);
return drain(gen);
}
function ensurePromise(maybePromise) {
return maybePromise.then
? maybePromise
: Promise.resolve(maybePromise);
}
function drain(gen, input) {
const returnResult = gen.next(input);
const resultPromise = ensurePromise(returnResult.value);
if(returnResult.done) return resultPromise;
return resultPromise.then(
result => drain(gen, result),
(err) => gen.throw(err)
);
}
const delay = ms => new Promise(res => setTimeout(res, ms));
const result = asyncFun(function * () {
yield delay(2000);
return "foobar";
})
const throwing = asyncFun(function * () {
yield delay(100);
throw "ERROR";
})
const test = asyncFun(function * () {
console.log("first");
yield delay(500);
console.log("second");
const res = yield result();
console.log(res);
try {
yield throwing();
} catch(err) {
console.log(err);
}
});
test();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment