Home > other >  Why OfficeJS changed code to asynchronous automatically?
Why OfficeJS changed code to asynchronous automatically?

Time:08-10

Hi I am new to JavaScript and still don't know why my code run the "console.log("ok")" before the previous code. I have read lots of articles and watched some videos but still can't find the answer. Appreciate your help!

Edited: It is very interesting. I added a new Promise to the code but the console.log still starts before the worksheet insert is finished. I may need to structure another function to get it work

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)
    })    
  }
}

CodePudding user response:

Because FileReader's methods work async, the code below reader.readAsDataURL(myFiles.files[i]); executes as the data is being read.

CodePudding user response:

Excel.run is asynchronous. (See the reference topic where it shows that it returns a Promise: Excel.run.) That means that the JavaScript engine starts it and immediately starts running the next line of code reader.readAsDataURL(myFiles.files[i]); That method is also asynchronous, so the engine starts it and immediately runs the console.log.

If you want the console.log to wait until after the previous code has finished, add the await keyword just to the left of the Excel.run and also just to the left of the reader.readAsDataURL(myFiles.files[i]);. You will probably also have to add the async keyword to the left of function importProjects().

  • Related