2017-10-08 6 views
1

非同期(async)ロード設定されたテーブル値、私は次のコードを使用して、選択したテーブルを埋めるためにしようとしています:MSワードAPI:オフィスのJavaScript APIを使用して

Word.run(function (context) { 

    var table = context.document.getSelection().parentTable;  
    table.load("values, rows/items/cells/items/body");  
    context.trackedObjects.add(table); 

    return context.sync().then(function() { 
     // loop over table 
     for (var row = 0; row < table.values.length; row++) { 
      for (var column = 0; column < table.values[row].length; column++) { 
       // use closures to keep cell index variables for ajax 
       (function (row, column, table, context) { 
        if ((table.values[row][column].trim() == 
          "" || !table.values[row][column]) && 
         table.values[row][0] && table.values[0][column]) { 

         $.ajax({ 
          url: "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/" + 
           table.values[row][0].replace(/\s/g, '') + 
           "/property/" + table.values[0][column] + "/txt" 
         }).done(function (data) { 

          // insert data 
          table.rows.items[row].cells.items[column].body.insertText(data); 
          console.log("data: " + data); 

          return context.sync().then(function() { 
           console.log("synced"); 
          }).catch(function (e) { 
           console.log("0"); 
           errorHandler(e); 
          }); 

         }).error(function (e) { 
          console.log("1"); 
          errorHandler(e); 
         }); 
        } else { 
         console.log(row + " " + column + " not beeing set, it is " + 
          table.values[row][column]); 
        } 
       })(row, column, table, context); 
      } 
     } 
    }).then(context.sync().then(
     function() { 
      console.log("last sync?"); 
     } 
    ).catch(function (e) { 
     console.log("2"); 
     errorHandler(e); 
    })); 
}).catch(function (e) { 
    console.log("3"); 
    errorHandler(e); 
}); 

しかし、どういうわけか、例外がスローされるように、これは動作しません。 - ログ(0)とインサートデータ部分の誤差("errorLocation":"TableRowCollection.getItem")に係る誤りの

ItemNotFound: ItemNotFound 

源です。

Ajaxの終了後すぐにその内容を更新する予定であるため、Wordにテーブルの変数を少し長くしておくように指示するにはどうすればよいですか?

答えて

1

この理由は、$.ajax()コールがバックグラウンドで発生している間は、機能がオンになり、完了するためです。 ajax()呼び出しが問題ではない間に実行をブロックする必要があります。

あなたは、この方法はいくつか行うことができますが、最も簡単には、単にあなたのajax()オプションでasync: false設定される可能性があります。挿入したい。また

$.ajax({ 
    url: "https://pubchem.ncbi.nlm.nih....", 
    async: false 
}).done(function (data) {}); 

を、あなたはinsertLocationと呼ばれる2番目のパラメータ(渡す必要がありますテキスト)をbody.insertText'Replace','Start'または'End'に設定します。