Skip to content

Instantly share code, notes, and snippets.

@nathggns
Last active August 29, 2015 14:22
Show Gist options
  • Save nathggns/d1a4745f68ae11a1f3c4 to your computer and use it in GitHub Desktop.
Save nathggns/d1a4745f68ae11a1f3c4 to your computer and use it in GitHub Desktop.
Await implemented in ES6.
function await(generatorFunction) {
let gen = generatorFunction();
/**
* @param {any?} err The error to throw in the generator, where yield was last called.
* @param {any?} result The result to pass to the genarator for the last call to yield
*/
function next(err, result) {
// If the last promise that was yielded was rejected,
// trigger an error inside the generator where yield was last called
if (err) {
gen.throw(
// Make sure that the error we're passing is actually an error and not just a string
err instanceof Error ? err : new Error(err)
);
}
// Get the next promise from the generator
let nextResult = gen.next(
result
);
let value = nextResult.value;
// If we're done with the generator, no need to keep going.
if (nextResult.done) {
return;
}
value.then(
// We have a value, call next again to pass it back into the generator and keep going
result => next(null, result),
// We have an error, throw it in the generator
e => next(e)
);
}
next();
}
function generateRandomNumber() {
return new Promise(resolve => setTimeout(() => resolve(Math.random()), 2000));
}
function makeError() {
return new Promise((r, reject) => reject('Some error'));
}
await(function*() {
try {
console.log('Starting random number generator');
console.log('Random number is', yield generateRandomNumber());
console.log('Starting another random number generator');
console.log('Another random number is', yield generateRandomNumber());
console.log('Throwing error');
yield makeError();
} catch (e) {
console.error('Caught error', e);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment