我的JavaScript代码在将值返回给事件监听器后执行。

huangapple go评论68阅读模式
英文:

My javascript code is executing after returning values to my event listener

问题

这是您提供的JavaScript代码的中文翻译部分:

使用JavaScript来读取Excel文件我使用exceljs库但我发现JavaScript函数会将响应返回给我的HTML事件监听器并继续执行并读取文件内容

我如何使这段代码在所有代码行完全执行后返回值请帮忙因为我是JavaScript的新手是根据许多在线资源构建的这段代码

readAndProcess(files) {
  return new Promise(resolve => {
    try {
      const file = files[0];
      let fileContent = [];
      const fileReader = new FileReader();

      fileReader.readAsArrayBuffer(file);

      fileReader.onload = (e) => {
        let result = e.target.result;
        let columns = [];
        let tableData = [];
        let size;
        if (result) {
          // 创建工作簿并添加工作表
          const wb = new ExcelJS.Workbook();
          wb.xlsx.load(result).then(workbook => {
            console.log(workbook, '工作簿实例');
            workbook.eachSheet((sheet, id) => {

              sheet.eachRow((row, rowIndex) => {
                console.log(rowIndex, '行索引');
                console.log(row);
                if (rowIndex === 1) {
                  columns = Object.entries(row.values).map(([k, v]) =>
                  ({
                    field: v,
                    headerText: v
                  })
                  );

                } else {
                  const part = {};
                  let index = 0;
                  Object.entries(row.values).map(([k, v]) => {
                    part[columns[index].field] = v;
                    index++;
                  }
                  );
                  tableData.push(part);
                };
              });
            });
          });
          resolve({
            success: true,
            result: {
              name: file.name,
              size: file.size,
              type: file.type,
              columns: columns,
              tableData: tableData
            },
            error: {
              detail: ''
            }
          });
        } else {
          resolve({
            success: false,

            error: {
              detail: '空文件:' + result
            }
          })
        }
      }
    } catch (err) {
      resolve({
        success: false,
        error: {
          detail: '读取文件时出错:' + err.detail
        }
      });
    }
  });
}

请注意,这是代码的翻译,不包含回答问题的部分。如果您有其他问题或需要进一步的帮助,请随时提出。

英文:

I'm making use of javascript to read the excel file with exceljs but I see that the javascript function is returning the response to my html event listerner and continuining execution and reading the content of file.

How can i make this code to return value after all lines of code are executed completely. Please help as I'm new to Javascript and have built this code by loooking at lot of online resources

 readAndProcess(files) {
return new Promise(resolve => {
try {
const file = files[0];
let fileContent = [];
const fileReader = new FileReader();
fileReader.readAsArrayBuffer(file);
fileReader.onload = (e) => {
let result = e.target.result;
let columns = [];
let tableData = [];
let size;
if (result) {
// Create workbook & add worksheet
const wb = new ExcelJS.Workbook();
wb.xlsx.load(result).then(workbook => {
console.log(workbook, 'workbook instance');
workbook.eachSheet((sheet, id) => {
sheet.eachRow((row, rowIndex) => {
console.log(rowIndex, 'rowIndex');
console.log(row);
if (rowIndex === 1) {
columns = Object.entries(row.values).map(([k, v]) =>
({
field: v,
headerText: v
})
);
} else {
const part = {};
let index = 0;
Object.entries(row.values).map(([k, v]) => {
part[columns[index].field] = v;
index++;
}
);
tableData.push(part);
//console.log(tableData);
};
});
});
});
resolve({
success: true,
result: {
name: file.name,
size: file.size,
type: file.type,
columns: columns,
tableData: tableData
},
error: {
detail: ''
}
});
} else {
resolve({
success: false,
error: {
detail: 'Empty File : ' + result
}
})
}
}
} catch (err) {
resolve({
success: false,
error: {
detail: 'Error while reading file : ' + err.detail
}
});
}
});
}
}

答案1

得分: 1

你面临的问题是函数似乎在完成文件的读取和处理之前就返回结果了。

这是因为读取文件的函数(它被称为“异步”函数)不会停下来等待文件被读取。相反,它开始读取文件,然后立刻转向下一步。所以,在完成文件读取之前,函数已经开始执行下一步(即返回结果)。

你需要做的是告诉函数在返回结果之前等待文件被读取和处理。

在你的代码中,你已经告诉它等待文件被读取(使用onload函数)。但你还需要告诉它在返回结果之前等待文件被处理(使用xlsx.load()函数)。

以下是你可以做的事情:

  1. 查找你的代码中的部分,找到wb.xlsx.load(result).then(workbook => {。这是你开始处理文件的地方。

  2. 在这部分的末尾,你应该看到单词resolve,后面跟着一些花括号{}。这是你告诉函数返回结果的地方。

  3. 将这个resolve部分(包括花括号内的所有内容)移动到xlsx.load()函数的末尾。这将告诉函数在文件被读取和处理之前等待,然后再返回结果。

你只需要将resolve部分移到正确的位置,你的函数就应该按预期工作。

英文:

The problem you're facing is that the function seems to be returning the result before it has finished reading and processing the file.

This is happening because the function that reads the file (it's called an "asynchronous" function) doesn't stop and wait for the file to be read. Instead, it starts reading the file and moves on to the next thing immediately. So, the function is moving on to the next thing (which is returning the result) before it has finished reading the file.

What you need to do is tell the function to wait until the file has been read and processed before returning the result.

In your code, you're already telling it to wait for the file to be read (using the onload function). But you also need to tell it to wait for the file to be processed (using the xlsx.load() function) before returning the result.

Here's what you can do:

  1. Look for the part of your code that says wb.xlsx.load(result).then(workbook => {. This is where you start processing the file.

  2. At the end of this part, you should see the word resolve followed by some curly brackets {}. This is where you're telling the function to return the result.

  3. Move this resolve part (with everything inside the curly brackets) to the end of the xlsx.load() function. This will tell the function to wait until the file has been read and processed before returning the result.

You just need to move the resolve part to the right place, and your function should work as expected.

huangapple
  • 本文由 发表于 2023年5月21日 20:30:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76299914.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定