Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

event: add foo method for bar #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions doc/api/events.md
Original file line number Diff line number Diff line change
Expand Up @@ -564,6 +564,17 @@ to indicate an unlimited number of listeners.

Returns a reference to the `EventEmitter`, so that calls can be chained.

### emitter.foo([callback])
<!-- YAML
added: v8.0.0
-->

* `callback` {Function}

Returns `'bar'` string synchronously if callback is omitted.
When `callback` is specified, it is executed asynchronously and return `true`.
The callback will receive the arguments `(err, 'bar')`. `err` is always `null`.

[`net.Server`]: net.html#net_class_net_server
[`fs.ReadStream`]: fs.html#fs_class_fs_readstream
[`emitter.setMaxListeners(n)`]: #events_emitter_setmaxlisteners_n
Expand Down
11 changes: 11 additions & 0 deletions lib/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,17 @@ EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
return $getMaxListeners(this);
};

EventEmitter.prototype.foo = function foo(callback) {
var err = null;
if (callback) {
process.nextTick(() => {
callback(err, 'bar');
});
return true;
}
return 'bar';
};

// These standalone emit* functions are used to optimize calling of event
// handlers for fast cases because emit() itself often has a variable number of
// arguments and can be deoptimized because of that. These functions always have
Expand Down
22 changes: 22 additions & 0 deletions test/parallel/test-event-emitter-foo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
'use strict';

const common = require('../common');
const EventEmitter = require('events');
const assert = require('assert');

const event1 = new EventEmitter();

const bar = 'bar';

// Sync API test
assert.strictEqual(event1.foo(), bar);

// Async API test
const event2 = new EventEmitter();

var ret = event2.foo(common.mustCall((err, arg) => {
assert.strictEqual(err, null);
assert.strictEqual(arg, bar);
}));

assert(ret);