events-once.js
2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
'use strict';
var common = require('./common');
var EventEmitter = require('../').EventEmitter;
var once = require('../').once;
var assert = require('assert');
function onceAnEvent() {
var ee = new EventEmitter();
process.nextTick(function () {
ee.emit('myevent', 42);
});
return once(ee, 'myevent').then(function (args) {
var value = args[0]
assert.strictEqual(value, 42);
assert.strictEqual(ee.listenerCount('error'), 0);
assert.strictEqual(ee.listenerCount('myevent'), 0);
});
}
function onceAnEventWithTwoArgs() {
var ee = new EventEmitter();
process.nextTick(function () {
ee.emit('myevent', 42, 24);
});
return once(ee, 'myevent').then(function (value) {
assert.strictEqual(value.length, 2);
assert.strictEqual(value[0], 42);
assert.strictEqual(value[1], 24);
});
}
function catchesErrors() {
var ee = new EventEmitter();
var expected = new Error('kaboom');
var err;
process.nextTick(function () {
ee.emit('error', expected);
});
return once(ee, 'myevent').then(function () {
throw new Error('should reject')
}, function (err) {
assert.strictEqual(err, expected);
assert.strictEqual(ee.listenerCount('error'), 0);
assert.strictEqual(ee.listenerCount('myevent'), 0);
});
}
function stopListeningAfterCatchingError() {
var ee = new EventEmitter();
var expected = new Error('kaboom');
var err;
process.nextTick(function () {
ee.emit('error', expected);
ee.emit('myevent', 42, 24);
});
// process.on('multipleResolves', common.mustNotCall());
return once(ee, 'myevent').then(common.mustNotCall, function (err) {
// process.removeAllListeners('multipleResolves');
assert.strictEqual(err, expected);
assert.strictEqual(ee.listenerCount('error'), 0);
assert.strictEqual(ee.listenerCount('myevent'), 0);
});
}
function onceError() {
var ee = new EventEmitter();
var expected = new Error('kaboom');
process.nextTick(function () {
ee.emit('error', expected);
});
return once(ee, 'error').then(function (args) {
var err = args[0]
assert.strictEqual(err, expected);
assert.strictEqual(ee.listenerCount('error'), 0);
assert.strictEqual(ee.listenerCount('myevent'), 0);
});
}
Promise.all([
onceAnEvent(),
onceAnEventWithTwoArgs(),
catchesErrors(),
stopListeningAfterCatchingError(),
onceError()
]).catch(function (err) {
console.error(err.stack)
process.exit(1)
});