23 Oct 2018

Wait for restoreState to finish

Viewer

When using certain functions, they may return before doing everything that you might expect. E.g. when viewer.restoreState() returns, the camera is still about to be modified - see above picture.

var viewerState;
function storeState() {
    viewerState = viewer.getState();    
}

function restoreState() {
    console.log('>>> before restoreState');
    viewer.restoreState(viewerState);
    console.log('>>> after restoreState');
}

If you want to make sure that your next operation will only be executed once the function you called has done everything that you'd expect it to, you could listen to the final event fired after the operations. 

In order to find that event, the easiest is to monitor all events before executing the function:
https://forge.autodesk.com/blog/event-monitor-viewer

In my case I can see that FINAL_FRAME_RENDERED_CHANGED_EVENT with value.finalFrame = true is the last event. So I could listen to that before executing restoreState() 

FINAL_FRAME_RENDERED_CHANGED_EVENT

The easiest might be to wrap the whole thing in a promise, in which case I can also use features like await - I just have to make my function async:

async function restoreStatePromise() {
    var restorePromise = new Promise(function (resolve, reject) {
        var listener = function (event) {
            if (event.value.finalFrame) {
                viewer.removeEventListener(
                    Autodesk.Viewing.FINAL_FRAME_RENDERED_CHANGED_EVENT, 
                    listener
                );
                resolve();
            }
        }

        // Wait for last render caused by camera changes
        viewer.addEventListener(
            Autodesk.Viewing.FINAL_FRAME_RENDERED_CHANGED_EVENT,
            listener
        );

        viewer.restoreState(viewerState);
    }); 
    
    console.log('>>> before restorePromise');
    await restorePromise;
    console.log('>>> after restorePromise');
}

Now if I run restoreStatePromise() I can see that the line after await restorePromise; is only executed once the camera has been fully restored as well:

restoreState in Promise

Related Article