javascript - 如何在 $.get 返回值之前停止代码运行?
问题描述
我正在尝试从文件中读取数据并使用 jquery 的 get 函数将其保存到数组中。但是因为get函数是异步的,所以$.get函数调用后的代码运行,数据是未定义的。如何仅在调用完成并返回数据后运行 $.get 函数调用之后的代码?
我尝试将 async 设置为 false,但控制台日志给出了它已被弃用的错误。
class CharacterDatabase{
constructor(fName){
this.fileText = readFile(fName);
this.fileText = this.fileText.split(/[\r\n]+/);
}
}
function readFile(fName){
console.log(fName);
$.get(fName, function(data){
return data;
}, "text");
}
var cd = new CharacterDatabase("text.txt");
错误:
main.js:32 Uncaught TypeError: Cannot read property 'split' of undefined at new CharacterDatabase (main.js:32) at main.js:85
被扔在控制台中。
第 32 行是:
this.fileText = this.fileText.split(/[\r\n]+/);
将 async 设置为 false 时,错误状态表明不推荐使用同步 XMLHTTPRequest。
解决方案
一个简单的解决方案是将调用包装在 a 中Promise
并使用async/await
:
class CharacterDatabase{
constructor(fName){
this.init();
}
}
async function init() {
this.fileText = await readFile(fName);
this.fileText = this.fileText.split(/[\r\n]+/);
}
async function readFile(fName){
console.log(fName);
await new Promise((resolve) => {$.get(fName, function(data){
resolve(data);
}, "text")});;
}
var cd = new CharacterDatabase("text.txt");
作为旁注,我通常不建议将任何 I/O 操作放在构造函数中。
推荐阅读
- amazon-athena - AWS Athena(Presto)如何将值是数组的映射转置为行
- javascript - 在 Promise 之前调用 setTimeout
- javascript - 警告:在 Formik 中从 submitForm() [TypeError: undefined is not an object (evalating '_props$field.open')] 中捕获了一个未处理的错误
- python - 创建一个没有无限循环的程序
- asp.net - 从控制器添加或删除部分视图时的 asp.net core mvc
- sql - 在 SQL DB2 中,我如何解密可以是 YYYYMMDD 或 YYYYDDMM 的日期字符串
- c# - 为什么我在使用 MvxWpfSetup 时收到错误 CS0310
作为 RegisterSetupType - android - 将 vue web 应用程序转换为 ios 和 android 应用程序的最简单方法
- python - 使用图像创建新帖子的测试不起作用。姜戈
- javascript - 如何在使用 webpack for npm 创建包构建时添加 svg