承诺的保证顺序运行,WordAPIJS
Guarantee order of promise running, Word API JS
我正在开发 Word 加载项,需要用从 API 中获取的值替换整个文档中的大量代码。我是 promises 的新手,并且在按顺序将替换 运行 时遇到问题,因此位置不会被打乱导致错过替换。到目前为止,我最好的尝试是:
function merge(documentFieldKeys) {
if (documentFieldKeys.length > 0)
Word.run(function(context) {
var key = documentFieldKeys.shift();
var results = context.document.body.search(key.Code, { matchWholeWord: false, matchCase: false });
context.load(results);
return context.sync().then(function() {
if (results.items.length > 0 && key.Value === "") {
missingFields.push(key.Description);
} else {
for (var i = 0; i < results.items.length; i++) {
results.items[i].insertText(key.Value, "replace");
}
}
})
.then(context.sync).then(merge(documentFieldKeys));
});
}
根据我对 promises 的理解,它应该处理第一项,然后在完成后通过短名单进行另一个替换。但是,它们的顺序看似随机。知道哪里出了问题吗?
问题是 .then(merge(documentFieldKeys))
。这意味着您正在立即调用合并功能。你想要做的是:
.then(function() {
return merge(documentFieldKeys);
})
.then(context.sync);
更新:
注意:第二个.then(context.sync)
是可选的,你实际上不需要它,因为Word.run
无论如何都会在最后刷新队列。但我发现显示它更清晰。
此外,对于它的价值:我写了一本关于 Office.js、“Building Office Add-ins using Office.js". In it I include a long primer on Promises, as well as TypeScript and async/await
, which makes working with Promises much easier. The book is available in e-book form at https://leanpub.com/buildingofficeaddins, with all profits to charity.
的书
我正在开发 Word 加载项,需要用从 API 中获取的值替换整个文档中的大量代码。我是 promises 的新手,并且在按顺序将替换 运行 时遇到问题,因此位置不会被打乱导致错过替换。到目前为止,我最好的尝试是:
function merge(documentFieldKeys) {
if (documentFieldKeys.length > 0)
Word.run(function(context) {
var key = documentFieldKeys.shift();
var results = context.document.body.search(key.Code, { matchWholeWord: false, matchCase: false });
context.load(results);
return context.sync().then(function() {
if (results.items.length > 0 && key.Value === "") {
missingFields.push(key.Description);
} else {
for (var i = 0; i < results.items.length; i++) {
results.items[i].insertText(key.Value, "replace");
}
}
})
.then(context.sync).then(merge(documentFieldKeys));
});
}
根据我对 promises 的理解,它应该处理第一项,然后在完成后通过短名单进行另一个替换。但是,它们的顺序看似随机。知道哪里出了问题吗?
问题是 .then(merge(documentFieldKeys))
。这意味着您正在立即调用合并功能。你想要做的是:
.then(function() {
return merge(documentFieldKeys);
})
.then(context.sync);
更新:
注意:第二个.then(context.sync)
是可选的,你实际上不需要它,因为Word.run
无论如何都会在最后刷新队列。但我发现显示它更清晰。
此外,对于它的价值:我写了一本关于 Office.js、“Building Office Add-ins using Office.js". In it I include a long primer on Promises, as well as TypeScript and async/await
, which makes working with Promises much easier. The book is available in e-book form at https://leanpub.com/buildingofficeaddins, with all profits to charity.