【问题标题】:Why OfficeJS changed code to asynchronous automatically?为什么 OfficeJS 自动将代码更改为异步?
【发布时间】:2022-08-10 06:45:51
【问题描述】:

嗨,我是 JavaScript 新手,但仍然不知道为什么我的代码在之前的代码之前运行 \"console.log(\"ok\")\"。我已经阅读了很多文章并观看了一些视频,但仍然找不到答案。感谢你的帮助!

编辑: 这很有趣。我在代码中添加了一个新的 Promise,但在工作表插入完成之前 console.log 仍然启动。我可能需要构建另一个函数来让它工作

function importProjects() {
  const myFiles = <HTMLInputElement>document.getElementById(\"file\");
  var numberofFiles = myFiles.files.length;

  for (let i = 0; i < numberofFiles; i++) {

    new Promise(function(resolve){
      let reader = new FileReader();

      reader.onload = (event) => {
        Excel.run((context) => {
          // Remove the metadata before the base64-encoded string.
          let startIndex = reader.result.toString().indexOf(\"base64,\");
          let externalWorkbook = reader.result.toString().substr(startIndex + 7);

          // Retrieve the current workbook.
          let workbook = context.workbook;

          // Set up the insert options.
          let options = {
            sheetNamesToInsert: [], // Insert all the worksheets from the source workbook.
            positionType: Excel.WorksheetPositionType.after, // Insert after the `relativeTo` sheet.
            relativeTo: \"Sheet1\" // The sheet relative to which the other worksheets will be inserted. Used with `positionType`.
          };

          // Insert the new worksheets into the current workbook.
          workbook.insertWorksheetsFromBase64(externalWorkbook, options);
          return context.sync();
        });
      };
      // Read the file as a data URL so we can parse the base64-encoded string.
      reader.readAsDataURL(myFiles.files[i]);
      resolve()
    }).then(function(){
      setTimeout(function(){
        console.log(\"ok\");
      },2000)
    })    
  }
}

    标签: excel office-js office-addins excel-addins excel-web-addins


    【解决方案1】:

    因为 FileReader 的方法异步工作,reader.readAsDataURL(myFiles.files[i]); 下面的代码在读取数据时执行。

    【讨论】:

      【解决方案2】:

      Excel.run 是异步的。 (参见参考主题,它显示它返回一个 Promise:Excel.run。)这意味着 JavaScript 引擎启动它并立即开始运行下一行代码 reader.readAsDataURL(myFiles.files[i]); 该方法也是异步的,因此引擎启动它并立即运行console.log

      如果您希望console.log 等到前面的代码完成后,请将await 关键字添加到Excel.run 的左侧以及reader.readAsDataURL(myFiles.files[i]); 的左侧。您可能还必须在function importProjects() 的左侧添加async 关键字。

      【讨论】:

      • 感谢你的回答。 “Excel.run 是异步的。”是关键。我已经编辑了代码,但 console.log 仍然在工作表插入完成之前启动。
      • 尝试将 context.sync 前面的“return”替换为“await”,或者将context.sync(末尾不带括号)放在then 中。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 2020-01-29
      • 2014-12-03
      • 1970-01-01
      • 2011-10-21
      相关资源
      最近更新 更多