Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

office js - Document not in sync after replace text

I'm trying to replace some text within a Word Online document but cannot get it to work.

'{{test}} , [[test]] , {test}' results in '13 , 2 , 3' and not '1 , 2 , 3'.

The first text seems to be processed twice.

Any help much appreciated!

Office.initialize = function(reason) {

    function ready() {

        var myTags = [
            { "value": "1", "text": "{{test}}" },
            { "value": "2", "text": "[[test]]" },
            { "value": "3", "text": "{test}" }
        ];

        async function FillTag(tag) {

            await Word.run(async function(context) {

                    var options = Word.SearchOptions.newObject(context);
                    options.matchWildCards = false;

                    var searchResults = context.document.body.search(tag.text, options);
                    context.load(searchResults, 'text');

                    await context.sync();

                    searchResults.items.forEach(function(item) {
                        item.insertText(tag.value, Word.InsertLocation.replace);
                    });
                    await context.sync();
                })
                .catch(function(error) {
                    console.log('Error: ' + JSON.stringify(error));
                    if (error instanceof OfficeExtension.Error) {
                        console.log('Debug info: ' + JSON.stringify(error.debugInfo));
                    }
                });
        }

        async function ProcessArray(myTags) {
            myTags.forEach(async function(tag) {
                await FillTag(tag);
            });
        }

        ProcessArray(myTags);
    }

    if (document.readyState !== 'loading') {
        ready();
    }
    else {
        document.addEventListener('DOMContentLoaded', ready);
    }
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your ProcessArray() function, try replacing the forEach statement with a for...of statement, as shown here:

async function ProcessArray(myTags) {
    for (var tag of myTags) {
        await FillTag(tag);
    }
}

Seems that the forEach statement fires off multiple asynchronous calls, without actually awaiting the completion of FillTag each time. If you replace the forEach statement with for...of as shown above, you should get the expected result.


UPDATE (additional info re code structure):

@DutchDan -- now that your initial issue has been resolved, here's a more optimal way to structure your code.

Office.initialize = function () {
    $(document).ready(function () {        
        FindAndReplace();
    });
};

async function FindAndReplace() {

    var myTags = [
        { "value": "1", "text": "{{test}}" },
        { "value": "2", "text": "[[test]]" },
        { "value": "3", "text": "{test}" }
    ];

    await Word.run(async (context) => {

        for (var tag of myTags) {
            var options = Word.SearchOptions.newObject(context);
            options.matchWildCards = false;

            var searchResults = context.document.body.search(tag.text, options);

            context.load(searchResults, 'text');

            await context.sync();

            searchResults.items.forEach(function (item) {
                item.insertText(tag.value, Word.InsertLocation.replace);
            });

            await context.sync();
        }
    }).catch(errorHandler);
}

Note:?You can quickly and easily try this snippet yourself by using Script Lab (https://aka.ms/getscriptlab). Simply install the Script Lab add-in (free), then choose "Import" in the navigation menu, and use the following Gist URL:?https://gist.github.com/kbrandl/b0c9d9ce0dd1ef16d61372cb84636898.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...