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