Skip to content

Instantly share code, notes, and snippets.

@julien-f
Last active April 12, 2018 17:41
Show Gist options
  • Save julien-f/ce91d57adf30ae33c4e757b5295fcd68 to your computer and use it in GitHub Desktop.
Save julien-f/ce91d57adf30ae33c4e757b5295fcd68 to your computer and use it in GitHub Desktop.
Async generator from generator
const makeAsyncGenerator = require('./make-async-generator')
const f = makeAsyncGenerator(function * () {
yield 'foo'
const value = yield Promise.resolve('bar') // yield promises to await them
yield value
try {
yield Promise.reject('baz')
} catch (value) {
yield value
}
})
for await (const value of f()) {
console.log(value)
}
'use strict'
function step (key, value) {
try {
var cursor = this.iterator[key](value)
} catch (error) {
return Promise.reject(error)
}
var then
return cursor.done || (value = cursor.value) == null || typeof (then = value.then) !== 'function'
? Promise.resolve(cursor)
: then.call(value, this.next, this.throw)
}
function AsyncIterator (syncIterator) {
this.iterator = syncIterator
this.next = step.bind(this, 'next')
this.return = step.bind(this, 'return')
this.throw = step.bind(this, 'throw')
}
const $$asyncIterator = (typeof Symbol === 'function' && Symbol.asyncIterator) || '@@asyncIterator'
AsyncIterator.prototype[$$asyncIterator] = function () {
return this
}
module.exports = function makeAsyncGenerator (generator) {
return function () {
return new AsyncIterator(generator.apply(this, arguments))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment