Skip to content

Instantly share code, notes, and snippets.

@mdanshin
Last active October 30, 2021 12:39
Show Gist options
  • Save mdanshin/257f13a8f9efca52cbacc08c7d5594a4 to your computer and use it in GitHub Desktop.
Save mdanshin/257f13a8f9efca52cbacc08c7d5594a4 to your computer and use it in GitHub Desktop.
Return value from eventEmitter
import EventEmitter from "events";
class Service {
getAllUsers() {
let search = function () {
return new Promise((resolve, reject) => {
let arr = []
const myEmitter = new EventEmitter()
myEmitter.on("event", () => {
arr.push(1,2,4,8)
console.log("an event occurred!")
setTimeout( () => {
resolve(arr)
},1000)
});
myEmitter.emit('event')
})
}
let res = search()
return res
}
}
class Controller {
constructor() {
this.service = new Service()
}
getUsers() {
const users = this.service.getAllUsers()
return users
}
}
const controller = new Controller()
// call one
controller.getUsers()
.then((result) => {console.log(result)})
.catch((e) => {console.log({error: e});})
// call two
console.log(await controller.getUsers());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment