我正在使用直接(非转换)JS构建一个Excel加载项,它在Excel桌面版本的IE11框架中执行。如果这很重要,我也使用Vue作为UI框架。我定义了以下两种方法(其中,但这两种方法最短,所以我将使用它们来演示我的问题):
protectSheet: function () {
return Excel.run(function (context) {
const sheet = context.workbook.worksheets.getActiveWorksheet();
return context.sync().then(function () {
sheet.protection.protect({
userInterfaceOnly: true,
drawingObjects: false
}); // allow inserting comments
return context.sync();
});
}).catch(function (error) {
console.log("error: " + error);
if (error instanceof OfficeExtension.Error) {
console.log("Debug info: " + JSON.stringify(error.debugInfo));
}
});
}
和
unProtectSheet: function () {
return Excel.run(function (context) {
const sheet = context.workbook.worksheets.getActiveWorksheet();
sheet.load("protection/protected");
return context.sync().then(function () {
if (sheet.protection.protected) {
sheet.protection.unprotect();
}
return context.sync();
});
}).catch(function (error) {
console.log("error: " + error);
if (error instanceof OfficeExtension.Error) {
console.log("Debug info: " + JSON.stringify(error.debugInfo));
}
});
}
然后我按照以下方式调用它们,希望它意味着第二个函数只在第一个完成后才开始执行:
onChange: function () {
this.unProtectSheet()
.then(this.protectSheet());
}
但是,第二个函数在第一个函数之后立即启动,而不等待第一个函数完成。我显然忽略了Office-JS承诺如何工作(或一般的承诺)。我在这做错了什么?
谢谢!
你很近。
但是,如果使用.then(funcName)
语法,则必须仅提供函数指针,而不是调用它。也就是说,而不是.then(this.protectSheet())
,放弃()
并将其保持为.then(this.protectSheet)
。
onChange: function () {
this.unProtectSheet()
.then(this.protectSheet);
}
或者,做:
onChange: function () {
this.unProtectSheet()
.then(function() {
return this.protectSheet();
});
}
顺便说一句,你最后也应该有一个“.catch”,以捕获任何一个函数中发生的任何错误。
...当然,使用async / await(例如,通过TypeScript或Babel或其他任何方式进行转换)看起来会更清晰。