Skip to content

Instantly share code, notes, and snippets.

@ericelliott
Last active September 10, 2018 08:32
Show Gist options
  • Save ericelliott/254566f24f765c222a7eeb39c6fecbca to your computer and use it in GitHub Desktop.
Save ericelliott/254566f24f765c222a7eeb39c6fecbca to your computer and use it in GitHub Desktop.
Assigning `yield` results...
const next = (iter, callback, prev = undefined) => {
// 2. The yielded value is extracted by calling
// .next(). We pass the previous value back into
// the generator for assignment.
const item = iter.next(prev);
const value = item.value;
// 4. The final value gets passed to the callback.
if (item.done) return callback(prev);
if (isPromise(value)) {
value.then(val => {
setImmediate(() => next(iter, callback, val));
});
} else {
setImmediate(() => next(iter, callback, value));
}
};
const asyncFunc = gensync(function* () {
// 1. yield value gets passed to the iterator.
// The function exits at the yield call time,
// and the `result` assignment doesn't happen
// until the generator is resumed.
const result = yield fetchSomething();
// 3. Does not run until .next() is called again.
// `result` will contain the value passed into
// the previous `.next()` call.
yield result + ' 2';
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment