Promises and Message Handlers

The first time a command causes an instance of the Client to connect to AMPS, the client creates a WebSocket connection that runs asynchronously. This asynchronous connection is responsible for processing incoming messages from AMPS, which includes both messages that contain data and acknowledgments from the server.

When you execute a command on the AMPS client, the execute() method creates and returns a Promise object that typically waits for an acknowledgment from the server and then resolves with the id of the command. (The exception to this is Client.publish(). For performance, the publish command does not wait for an acknowledgment from the server before returning.)

Message handlers provided for message processing must be aware of the following considerations:

  • For maximum performance, do as little work in the message handler as possible. For example, if you use the contents of the message to perform an extensive calculation, a message handler that passes data into a WebWorker instance will typically perform better than a message handler that does this calculation in place.

  • While your message handler is running, the connection that calls your message handler is no longer receiving messages. This makes it easier to write a message handler because you know that no other messages are arriving from the same subscription. However, this also means that you cannot use the same client that called the message handler to send commands to AMPS. Acknowledgments from AMPS cannot be processed and your application will block while waiting for the acknowledgment. Instead, enqueue the command in a work queue to be processed by a separate worker or use a different client object to submit the commands.

Last updated