如何使用 nestjs 微服务让函数等待返回,直到完成 ClientProxy 订阅
How to make a function wait returning until a ClientProxy subscribe is done, using nestjs microservices
我有这个调用另一个微服务函数的函数,我想 return 在订阅中添加所有元素后的标签。
这是在 nestjs 中使用微服务完成的。
因为现在这只是 return 空数组,但我希望它 return 包含元素。
有人知道解决办法吗?谢谢
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;
}
您不需要 async
方法。 async
只有当你也使用 await
时才有意义,这里 await
不是必需的。
只是 return 一个常规的承诺:
getAllTags() {
return this.postMicroserviceProxy
.send<any>("get_posts", "")
.toPromise()
.then(response => response.flatMap(element => element.tags));
}
因为它 return 是一个承诺,你仍然可以 await
这个功能,但是:
async test() {
const tags = await foo.getAllTags();
}
我有这个调用另一个微服务函数的函数,我想 return 在订阅中添加所有元素后的标签。
这是在 nestjs 中使用微服务完成的。
因为现在这只是 return 空数组,但我希望它 return 包含元素。
有人知道解决办法吗?谢谢
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;
}
您不需要 async
方法。 async
只有当你也使用 await
时才有意义,这里 await
不是必需的。
只是 return 一个常规的承诺:
getAllTags() {
return this.postMicroserviceProxy
.send<any>("get_posts", "")
.toPromise()
.then(response => response.flatMap(element => element.tags));
}
因为它 return 是一个承诺,你仍然可以 await
这个功能,但是:
async test() {
const tags = await foo.getAllTags();
}