我有paragraphsArray
个段落对象。我有keywordRanges
个段落和关键字的索引。我试图迭代keywordRanges并从段落对象获取关键字的RangeObject。
但是在第一次迭代后代码失败并出现此错误:
PropertyNotLoaded: The property 'items' is not available. Before reading the property's value, call the load method on the containing object and call "context.sync()" on the associated request context.
参考代码:
var myObject = {
"2":{
"keywords":["the","which","eye"]
},
"4":{
"keywords":["lorem","ipsum"]
},
"9":{
"keywords":["hellow","world","foo","bar"]
}
},
paragraphsArray = [],
keywordRanges = []
Word.run((context) => {
// Create a proxy object for the document body.
var paragraphs = context.document.body.paragraphs
// Queue a commmand to get the OOXML contents of the body.
context.load(paragraphs, 'text, font, style');
// Synchronize the document state by executing the queued commands,
// and return a promise to indicate task completion.
return context.sync()
.then(() => {
// push paragraph range objects to an array
for (var i = 0; i < paragraphs.items.length; i++) {
paragraphsArray.push(paragraphs.items[i])
}
$.each(myObject, (key, value) => {
$.each(value.keywords, (idx, keyword) => {
// add the paragraph range object for the corresponding keyword to an array
var obj = {range:paragraphsArray[key], keyword:keyword}
keywordRanges.push(obj);
})
})
})
.then(()=>{
if(keywordRanges.length > 0){
$.each(keywordRanges, (idx, obj) =>{
// search keyword in the paragraph range object
// obj.range is Paragraph Range object
var searchKeywordResults = obj.range.search(obj.keyword, { matchWholeWord: true})
context.load(searchKeywordResults, 'text, font')
return context.sync().then(() => {
for (var i = 0; i < searchKeywordResults.items.length; i++) {
console.log(searchKeywordResults.items[i])
}
})
})
}
})
})
答案 0 :(得分:1)
在循环中有一个context.sync,后跟一个then(),这意味着每次迭代循环都有一个新的Promise链。在Word.run()结束之前,所有的承诺都必须得到解决。