Skip to content

Instantly share code, notes, and snippets.

@francisrstokes
Created December 28, 2018 23:50
Show Gist options
  • Save francisrstokes/e6fcacb5a8c5050224093e08d05af6bb to your computer and use it in GitHub Desktop.
Save francisrstokes/e6fcacb5a8c5050224093e08d05af6bb to your computer and use it in GitHub Desktop.
Async/Await in 5 lines
const interpret = iterator => last => {
const {value, done} = iterator.next(last);
return (done) ? Promise.resolve(value) : value.then(interpret(iterator));
};
const asyncAwait = g => interpret(g())();
// ... Usage ...
const addOneSoon = (x, t) => new Promise(resolve => {
setTimeout(() => resolve(x+1), t);
});
asyncAwait(function* () {
const a = yield addOneSoon(0, 1000);
const b = yield addOneSoon(40, 500);
return a + b;
}).then(console.log);
// -> 42 (After 1.5 seconds)
@long-kr
Copy link

long-kr commented Sep 5, 2024

like

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment