[英]FileReader readAsText() async issues?
I have implemented the following code to parse a CSV via a <input type="file" />
selection: 我已经实现了以下代码来通过
<input type="file" />
选择来解析CSV:
export async function parse(file: File) {
let content = '';
const reader = new FileReader();
reader.onload = function(e: any) {
content = e.target.result;
};
await reader.readAsText(file);
const result = content.split(/\r\n|\n/);
return result;
}
If I run this code and put a breakpoint on the line where I declare result
, it retrieves the contents of the file successfully. 如果我运行此代码并在我声明
result
的行上放置一个断点,它会成功检索文件的内容。 If I do not put any breakpoint, the content is empty. 如果我没有放置任何断点,则内容为空。 As you can see, I added
await
to the line where the reader reads the file as text, but it's still not working. 正如您所看到的,我添加了
await
读者将文件作为文本读取的行,但它仍然无效。
await
doesn't help here. await
在这里没有帮助。 readAsText()
doesn't return a Promise
. readAsText()
不返回Promise
。
You need to wrap the whole process in a Promise
: 您需要将整个过程包装在
Promise
:
export function parse(file: File) {
// Always return a Promise
return new Promise((resolve, reject) => {
let content = '';
const reader = new FileReader();
// Wait till complete
reader.onloadend = function(e: any) {
content = e.target.result;
const result = content.split(/\r\n|\n/);
resolve(result);
};
// Make sure to handle error states
reader.onerror = function(e: any) {
reject(e);
};
reader.readAsText(file);
});
}
Here is the JSBin I have tried and it work like a charm. 这是我尝试的JSBin ,它的工作就像一个魅力。
function parse(file) {
const reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event) {
// The file's text will be printed here
console.log(reader.result)
}
}
Updated: 更新:
I write you a Promise version. 我给你写了一个Promise版本。
async function parse(file) {
const reader = new FileReader();
reader.readAsText(file);
const result = await new Promise((resolve, reject) => {
reader.onload = function(event) {
resolve(reader.result)
}
})
console.log(result)
}
To generalize @zero298's answer a tiny bit, here's the generic Promise-based wrapper around FileReader
- 为了概括@ zero298的答案,这里是
FileReader
的基于Promise的通用包装 -
// get contents of a file as obtained from an html input type=file element
function getFileContents(file) {
return new Promise((resolve, reject) => {
let contents = ""
const reader = new FileReader()
reader.onloadend = function (e) {
contents = e.target.result
resolve(contents)
}
reader.onerror = function (e) {
reject(e)
}
reader.readAsText(file)
})
}
used like so - 像这样使用 -
async function parse(file) {
const contents = await getFileContents(file)
const result = contents.split(/\r\n|\n/)
return result
}
or in the general case, 或者在一般情况下,
async function show(file) {
const contents = await getFileContents(file)
alert(contents)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.