Office-JS Excel API:正确链接诺言的问题

时间:2019-05-01 01:31:52

标签: excel office-js

我正在使用直接(非转译)JS构建Excel加载项,该JS在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承诺(或一般而言)的工作方式的观点。我在这里做错了什么?

谢谢!

1 个答案:

答案 0 :(得分:1)

你非常亲近。

但是,如果使用.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或其他方法进行转译)看起来会更加干净。