我想从目录中读取TXT文件,我的代码可以正常工作
window.onload = () => {
fetch("file.txt")
.then(res => res.text())
.then(data => {
console.log(data);
});
};
但是我想在这样的函数中执行fetch调用:
window.onload = () => {
const filePath = "file.txt";
const fileData = readDataFile(filePath);
console.log(fileData);
};
const readDataFile = path => {
fetch(path)
.then(res => res.text())
.then(data => {
return data;
});
};
但是在这种情况下,它返回undefined
。
它的另一个问题是,如果发生错误,我将无法捕获,我尝试将catch
添加到Promise中,然后将throw
添加到错误中,但是它不起作用。这是我尝试过的:
window.onload = () => {
fetch("file.txt")
.then(res => res.text())
.then(data => {
console.log(data);
})
.catch(err => {
throw new Error("ERROR!");
});
};
这有效:
const readDataFile = async path => {
try {
const response = await fetch(path);
const data = await response.text();
return data;
} catch (err) {
console.log('Cannot read file.');
}
}
window.onload = async () => {
const filePath = 'data.txt';
const fileData = await readDataFile(filePath);
console.log(fileData);
}
但是,再次,catch方法不起作用吗?我做错了吗?