Skip to content

Instantly share code, notes, and snippets.

@zero1five
Last active June 1, 2019 11:55
Show Gist options
  • Select an option

  • Save zero1five/408c59f49bb9d2ec7706fde415468869 to your computer and use it in GitHub Desktop.

Select an option

Save zero1five/408c59f49bb9d2ec7706fde415468869 to your computer and use it in GitHub Desktop.
for await of in `on`
const { on, EventEmitter } = require('events');
const assert = require('assert');
async function error() {
const ee = new EventEmitter();
const _err = new Error('kaboom');
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 233);
ee.emit('foo', Symbol('233'));
// ee.emit('error', _err);
});
const iterable = on(ee, 'foo');
let looped = false;
let thrown = false;
try {
// eslint-disable-next-line no-unused-vars
for await (const event of iterable) {
looped = true;
}
} catch (err) {
thrown = true;
assert.strictEqual(err, _err);
}
// ----------- not execute
assert.strictEqual(thrown, true);
assert.strictEqual(looped, true);
setInterval(() => {console.log('....')}, 2000)
}
error();
// -------------------
var asyncIterable = {
[Symbol.asyncIterator]() {
return {
i: 0,
next() {
if (this.i < 3) {
return Promise.resolve({ value: this.i++, done: false });
}
return Promise.resolve({ done: true });
}
};
}
};
(async function() {
for await (num of asyncIterable) {
console.log(num);
}
setInterval(() => {console.log('....')}, 2000)
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment