首页 > 解决方案 > 如何在 $.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。

标签: javascriptjqueryajax

解决方案


一个简单的解决方案是将调用包装在 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 操作放在构造函数中。


推荐阅读