I have this function which calls another microservice function and I want to return the tags after all elements are added in the subscribe.
This is done in nestjs using microservices.
As it is right now this just returns the empty array, but I want it to return it with the elements.
Does anyone know a fix? thansk
private microservicesOptions: ClientOptions = {
transport: Transport.TCP,
options: {
host: host,
port: 3006
}
}
private filterProxy: ClientProxy;
constructor() {
this.filterProxy = ClientProxyFactory.create(this.microservicesOptions);
}
async getAllTags() {
let tags = []
this.postMicroserviceProxy.send<any>("get_posts", "").subscribe(response => {
response.forEach(element => {
element.tags.forEach(tag => {
tags.push(tag)
})
});
});
return tags;
}
CodePudding user response:
You don't need an async method. async only makes sense when you also use await, and await is not necessary here.
Just return a regular promise:
getAllTags() {
return this.postMicroserviceProxy
.send<any>("get_posts", "")
.toPromise()
.then(response => response.flatMap(element => element.tags));
}
Because it returns a promise, you can still await this function, though:
async test() {
const tags = await foo.getAllTags();
}
