2017-09-13 8 views
0

Office.js経由で新しいWord文書の段落のセットを更新しようとしています。以下のコードは、期待通りに順番にループする非同期チェーンです。段落を最初に検索すると、rangeCollectionが正しく返されますが、後続のすべての呼び出しでNULL seachResults.itemsオブジェクトが返されます。Office.jsの新しいWord文書で複数の段落検索(更新あり)を実行するにはどうすればよいですか?

残念ながら、私は完全なドキュメント検索を行うことができないという贅沢はありません。私はすでに段落インデックスの既知のリストを持っているので、それらの段落内の既知のテキストと一緒に見つけ出す必要があります。

アイデアはありますか?

var processDocAsync = function (context, paragraphs, onComplete) { 

    // A recursive helper function to work on the n'th paragraph 
    function getAndProcessParagraph(index) { 

     // stop processing 
     if (index == paragraphs.items.length) { 
      onComplete(); 
     } else { 
      // Main recursive case 

      // search the indexth paragraph 
      var options = Word.SearchOptions.newObject(context); 
      options.matchCase = false 

      var searchResults = paragraphs.items[index].search('the', options); 
      context.load(searchResults, 'text, font'); 

      context.sync().then(function() { 

       // Highlight all the "THE" words in this paragraph 
       try { 

        // Queue a command to change the font for each found item. 
        if (searchResults.items) { 
         for (var j = 0; j < searchResults.items.length; j++) { 
          searchResults.items[j].font.color = '#FF0000' 
          searchResults.items[j].font.highlightColor = '#FFFF00'; 
          searchResults.items[j].font.bold = true; 
         } 
        } 
       } catch (myError) { 
        console.log(myError.message); 
       } 

       // Synchronize the document state by executing the queued-up commands, 
       // then move on to the next paragraph 
       return context.sync().then(getAndProcessParagraph(index + 1)); 
      }); 
     } 
    } 

    // Begin the recursive process with the first slice. 
    getAndProcessParagraph(0); 
} 

var openProcessedDoc = function (base64str, documentId) { 

    Word.run(function (context) { 

     var myNewDoc = context.application.createDocument(base64str); 
     context.load(myNewDoc); 

     var paragraphs = context.document.body.paragraphs; 
     paragraphs.load(paragraphs, 'text, font'); 

     return context.sync().then(function() { 
      processDocAsync(context, paragraphs, processCompleted) 
     }); 
    }); 
}; 

var processCompleted = function() { 
    console.log('Process completed'); 
} 

答えて

0

優れた質問です。これは、約束と非同期パターンを持つコレクション内でコレクションをトラバースする典型的なケースです。

Please setup script lab(すばらしいアドインでコードスニペットを試すことができます) yamlの読み込み方法については、7:46 on this videoに移動してください。

load this yamlスクリプトラボで、これを行う方法の例を参照してください。サンプルはあなたが必要とするものではありません(基本的には段落内の単語の集合を横断します)が、あなたのシナリオに合わせてこのパターンを模倣できることを願っています。

ハッピーコーディング!

関連する問題