-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheventEmitter.js
More file actions
50 lines (40 loc) · 1.5 KB
/
Copy patheventEmitter.js
File metadata and controls
50 lines (40 loc) · 1.5 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
const EventEmitter = require('events');
const eventEmitter = new EventEmitter();
const getResponsePromise = () => {
return new Promise((resolve) => {
setTimeout(() => {
resolve('inside getResponsePromise');
}, 1000);
}).then((result) => {
console.log("Location : ", result);
return result;
});
}
const promiseWithParams = (param, data) => {
// console.log("Promise with params: ", param, data);
return new Promise((resolve, reject) => {
if (param === 'test') {
// Correct approach: resolve the promise when the event fires, and remove the listener after firing.
const handler = (data) => {
console.log("Data: ", data);
resolve(data); // resolve only when 'test' event is emitted
eventEmitter.removeListener('test', handler); // cleanup
};
eventEmitter.on('test', handler);
eventEmitter.emit('test', data); // <-- Emit the event with the provided data so the promise can resolve
} else {
reject(new Error('Invalid parameter'));
}
});
}
getResponsePromise().then((result) => {
console.log("Location: ", result);
});
promiseWithParams('test', "inside promiseWithParams").then((result) => {
console.log("Location: ", result);
});
console.log("--------------------------------");
eventEmitter.on('test', (data) => {
console.log("Data: ", data);
});
eventEmitter.emit('test', "This is how it ends !!");