Search code examples
extendscriptadobe-premiere

Loop is finishing faster than file object read/write/import


I've never had this problem with extendscript before and I thought extendscript was synchronous. I'm looping thru an array: for each object in the array I'm opening, reading and updating an xml and then importing it into PPro. I think the loop is finishing faster than the file update and import - no files are being imported.

If I alert(array[i]) each time everything works but once I comment out the alert the files no longer import.

function importXML(targetFile){
    app.project.importFiles([targetFile], 1); // 1 == suppress UI
    updateEventPanel('Media imported for ' + show);
    return 'success';
}


function processXML(obj){
    var shows = obj.shows;
    // alert(shows.length);

    var currentShow = obj.shows[0];

    for(var i = 0; i < shows.length-1; i++){
        var xmlDoc = obj.targetXml;
        var show = obj.shows[i+1];
        // alert('currentShow: ' + currentShow);
        // alert('show: ' + show);

        var currentValue1 = new RegExp('<Name>'+ currentShow, 'g');
        var currentValue2 = new RegExp('HIGHLIGHT_VERSIONING/'+ currentShow, 'g');
        var newValue1 = '<Name>'+ show;
        var newValue2 = 'HIGHLIGHT_VERSIONING/'+ show;

        var myFile = new File(xmlDoc);
            myFile.open('e', undefined, undefined);

        var inText = myFile.read();
            inText = inText
                .replace(currentValue1, newValue1)
                .replace(currentValue2, newValue2);

        myFile.seek(0);
        myFile.write(inText);
        myFile.close();

        updateEventPanel('XML updated for ' + show);

        importXML(xmlDoc);
        // updateEventPanel('Media imported for ' + show);

        currentShow = show;
    };
}

Solution

  • I've run into a similar issue before when reading data from a static csv file...I had an onChange event for scriptUI drop downs, but they would only half populate like as of it timed-out halfway through reading. I went in search of a settimeout-like function and I found that ESTK has a $.sleep() method for adding a delay:

    sleep()
    $.sleep(milliseconds)
    
    milliseconds    
    The number of milliseconds to wait.
    Suspends the calling thread for the given number of milliseconds.
    
    During a sleep period, checks at 100 millisecond intervals to see 
    whether the sleep should be terminated. This can happen if there is 
    a break request, or if the script timeout has expired.
    
    Returns: undefined
    

    You can read all about the dollar object, among other things, in the aenhancers estk doc: https://estk.aenhancers.com/8%20-%20ExtendScript%20Tools%20and%20Features/dollar-object.html