Promises

HOOPS Communicator is built with an asynchronous client / server architecture. This allows you to deliver a highly responsive experience for models that are hundreds of megabytes or larger with extremely low time to the first user interaction. To facilitate this, the client must be in constant communication with the server to send commands and receive data. HOOPS Communicator API calls are non-blocking and make use of the asynchronous facilities of JavaScript notify the caller when requested data has become available to the client.

Promises are a language-level feature of JavaScript that makes reasoning about asynchronous code easier for programmers by allowing them to chain function calls together in a linear manner.

A solid understanding of asynchronous JavaScript programming concepts is helpful for using the HOOPS Communicator API. The Mozilla Developer Network page on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise provides a thorough discussion of the topic as well as links to additional resources.

The following code listing shows an example of HOOPS Communicator API calls in a promise chain:

        viewer.view
            .pickFromPoint(mousePos, pickConfig)
            .then((selectionItem) => {
                return selectionItem.getNodeId();
            })
            .then((selectedNodeId) => {
                return viewer.model.getNodeProperties(selectedNodeId);
            })
            .then((nodeProperties) => {
                displayNodePropertiesToUser(nodeProperties);
            });

Async / await

While it is easy to see how the promise syntax makes the flow of code resemble the order of operations as they should be executed, modern browsers can do even better. The Async / Await syntax further simplifies working with asynchronous JavaScript code by allowing us to write our asynchronous code much like we would write normal, synchronous code. The Mozilla Developer Network page on Async / Await has detailed descriptions and examples of these concepts.

The following code listing shows the example above rewritten using async / await:

    async function displayNodeProperties(
        mousePos: Communicator.Point2,
        pickConfig: Communicator.PickConfig,
    ) {
        let selectionItem = await viewer.view.pickFromPoint(mousePos, pickConfig);
        let nodeProperties = await viewer.model.getNodeProperties(selectionItem.getNodeId());
        displayNodePropertiesToUser(nodeProperties);
    }