Last active
April 12, 2018 17:41
-
-
Save julien-f/ce91d57adf30ae33c4e757b5295fcd68 to your computer and use it in GitHub Desktop.
Async generator from generator
This file contains 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 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) | |
} |
This file contains 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
'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