如何在pubnub中按顺序发布消息?

问题描述

所以问题是如何在pubnub中按顺序发送消息。

示例:我添加文字和 2 张图片。流程应该是 => 将文本作为第一条消息发送,将第一张图像作为第二条消息发送,将第二张图像作为第三条消息发送。他们应该一一出现在pubnub历史上。

假设我在 sendarray 变量中拥有所有这些东西

(async () => {
  for await (const item of sendarray) {
    pubnub.publish({ 
      channel: currentChannel,message: item,})
  }
})();

我已经尝试过类似的方法,但它不起作用。

解决方法

这几乎是正确的,只是 await 关键字的位置错误。

(async () => {
  for (const item of sendArray) {
    await pubnub.publish({ 
      channel: currentChannel,message: item,})
  }
})();

这是因为发布方法是您需要等待的异步操作。 for await 是用于迭代异步可迭代对象的特殊构造,因此无需在此处使用它。 For 循环尊重 async 块内的 await 关键字。