简体   繁体   English

如何避免 office-js 中的 context.loads() 过多

[英]How to avoid too many context.loads() in office-js

I've read Michael Zlatkovsky's very excellent "Building Office Add-ins", and one of the things he says is attempt to avoid costly async calls to context.load() .我读过 Michael Zlatkovsky 非常出色的“Building Office Add-ins”,他说的其中一件事是尝试避免对context.load()代价高昂的async调用。 He mentions that he would be hard pressed to find a scenario where he would need more than 2.他提到他很难找到需要超过 2 个的场景。

My question is this: If processing all the paragraphs in the entire document, I need to get at some very deeply nested elements (eg document.paragraphs.paragraph.listItem.siblingIndex ).我的问题是:如果处理整个文档中的所有段落,我需要获取一些非常深的嵌套元素(例如document.paragraphs.paragraph.listItem.siblingIndex )。 If I start from the document, the only way I can see to do this is:如果我从文档开始,我能看到的唯一方法是:

paragraphs =  context.document.body.paragraphs;
paragraphs.load("items");
await context.sync();
for (var i =0; i<paragraphs.items.length; i++){
      paragraphs.items[i].load("listItemOrNullObject");
}
await context.sync();

//.... Then iterate through every item in paragraph to load(siblingIndex)

await context.sync();

//finally am able to process stuff that requires properties from all nested levels

Is this the correct way to go about this?这是解决这个问题的正确方法吗? ie one sync() call for each nested level for which one needs properties?即对每个需要属性的嵌套级别进行一次sync()调用? Seems like many async calls to sync() .似乎有很多对sync()异步调用。 Is this avoidable in any way?这是可以避免的吗? I would imagine this is a common use case.我想这是一个常见的用例。

You can load properties from deep levels by using forward slashes in the parameter that you pass to the load method.您可以通过在传递给 load 方法的参数中使用正斜杠从深层加载属性。 This technique lets you load nested levels with a single context.sync().此技术允许您使用单个 context.sync() 加载嵌套级别。

The following code is from the same book you mentioned gets the name property of all the columns in all the tables in all the worksheets:以下代码来自您提到的同一本书,获取所有工作表中所有表中所有列的name属性:

Excel.run(async (context) => {
 workbook.load("worksheets/tables/columns/name");

 await context.sync();

 var secondColumnOfFirstTableOnThirdSheet =
  workbook
 .worksheets.items[2]
 .tables.items[0]
 .columns.items[1];

 console.log("The ridiculously-nested column name was " +
 secondColumnOfFirstTableOnThirdSheet.name);

}).catch(...);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM