Created
February 27, 2022 21:42
-
-
Save alpox/a04744029bab0bf6a78b81ff0b1dbe28 to your computer and use it in GitHub Desktop.
Async await
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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