23 Oct 2018

Wait for restoreState to finish


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');
    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:

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() 


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) {

        // Wait for last render caused by camera changes

    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

Posted By

Adam Nagy

Follow @AdamTheNagy Adam Nagy joined Autodesk back in 2005 and has been providing programming support, consulting, training and evangelism to external developers. He started his career in Budapest, then worked in Prague for 3 years and now lives in South England, UK. At the moment focusing on Inventor and Fusion 360, plus cloud and mobile related technologies. Adam has a degree in Software Engineering and has...