Google PubSub 中的 PubSub.Subscriptions() 和 Topic.getSubscriptions() 有什么区别?

What is the difference between PubSub.Subscriptions() and Topic.getSubscriptions() in Google PubSub?

我创建了一个使用 Google PubSub NodeJS SDK 处理 PubSub 消息传递的程序。 在开发这个时,我注意到 NodeJS 库和文档显示了两种在 Google PubSub 中检索活动订阅的方法:

  1. PubSub.subscriptions('SubscriptionName') docs
  2. PubSub.topic('TopicName).getSubscriptions() docs

我知道第二个选项可能只列出与某个主题相关的订阅,但我对幕后工作更感兴趣。

在我的第一次尝试中,我使用了第二个选项来检索我的订阅,并且在 运行 应用程序时有效,但是我 运行 在我的单元测试中尝试模拟调用时超时,并且我无法修复它。我切换到第一种方法,它不使用 Promise 而只是 returns 一个普通的 Subscription 对象,这在我的单元测试中工作得很好

不使用基于承诺的调用是否有缺点,因为它可能不会产生最新的结果?如果不是,为什么有两种选择,一种是基于承诺而另一种不是?

这两个 API 的作用截然不同。第一个one creates a Subscription object in the client that can be used for receiving messages. It does not retrieve any state from the Cloud Pub/Sub service. Therefore, there is no asynchronous work to do and it need not return a promise. The second one actually goes to the Cloud Pub/Sub service, retrieves the list of subscriptions for the topic, and creates a Subscription object for each one.

如果您知道要为其接收消息的订阅的名称并且可以合理地确信它存在,则使用 PubSub.subscriptions('SubscriptionName')。如果您尝试通过调用 subscription.on('message', messageHandler); 开始接收有关此订阅的消息,但它不存在,则会发出错误。

如果您不知道订阅的名称,而是需要获取列表并从该主题的所有订阅列表中选择要从中接收消息的订阅,请使用 PubSub.topic('TopicName).getSubscriptions()打电话。

若要进一步了解为什么模拟 getSubscriptions() 调用不起作用,可能需要查看您用来模拟它的代码。