-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path5-once.js
33 lines (25 loc) · 827 Bytes
/
5-once.js
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
'use strict';
// Task: why do we receive array in array as a `result`?
// Fix code to receive single array in `result`.
// Compare `events.once` with `EventEmitter.prototype.once`
// and swap them in the following example:
const { EventEmitter, once } = require('node:events');
const application = new EventEmitter();
const electronics = [
{ name: 'Laptop', price: 1500 },
{ name: 'Keyboard', price: 100 },
{ name: 'HDMI cable', price: 10 },
];
application.on('buy', (items) => {
if (!Array.isArray(items)) {
application.emit('error', new Error('Array expected'));
} else {
application.emit('purchase', items);
}
});
const main = async () => {
const result = await once(application, 'purchase');
console.log(result);
};
main();
application.once('error', console.error).emit('buy', electronics);