首页 > 解决方案 > 带有 JQuery 的 Typescript Promise 似乎运行了两次?

问题描述

我以为我正在慢慢掌握 Typescript/JS 中的 Promises,但这让我感到困惑。

我正在尝试使用 Promises 等待两个 JQuery getJSON 请求完成。使用我的浏览器 - 访问本地服务器 - 一切正常:但是我从用户那里得到了一个 HAR 日志,显示 getJSON 请求是重复的,并且 Promise 解决了两次。我根本无法重现这种行为,但它对用户来说是一致的,使用禁用插件的 Chrome 71。

我希望控制台输出是这样的......

   Document Ready
   File Loaded
   Query Loaded
   Got file and query

但相反 - 在这台用户机器上,它更像这样

   Document Ready
   File Loaded
   Query Loaded
   File Loaded
   Query Loaded
   Got file and query
   Got file and query

这是稍微简化的代码。

class Panel {
  private pathName: string;

  constructor(name: string) {
    this.pathName = name;
  }

  async loadStuff(buster: string): Promise<any> {
    // start to fetch the file JSON. 
    let fileP = $.getJSON(this.pathName + "/file.json", { mtime: buster });

    // start to run the query
    let queryP = $.getJSON("/api/query");

    return fileP.then(async (data: any) => {
      console.log("File loaded");
      this.dosomething(data.objects);

      return queryP.then((qdata: any) => {
        console.log("Query loaded");
        this.dosomethingelse(qdata);
      });
    }
      , () => {
        alert("Error loading '" + this.pathName + "/file.json'");
      });
  }
}

$(() => {

  console.log("Document ready");

  let bp: Panel = new Panel("foo");  
  let promise: Promise<void> = bp.loadStuff("test");

  promise.then(() => {
    console.log("Got file and query");
  });

我最好的猜测是我对仅由于用户计算机上的网络时间条件而触发的 Promise 做错了。但我不知道是什么!

标签: jquerytypescriptpromisegetjson

解决方案


这可能不是一个直接的答案,但如果您等待您的承诺,那么对您的代码进行推理会更容易。

class Panel {
  private pathName: string;

  constructor(name: string) {
    this.pathName = name;
  }
  async loadStuff(buster: string): Promise<any> {
    try {
      // start to fetch the file JSON.
      let fileP = await $.getJSON(this.pathName + '/file.json', {
        mtime: buster,
      });
      this.dosomething(fileP.objects);

      // start to run the query
      let queryP = await $.getJSON('/api/query');
      this.dosomethingelse(queryP);
    } catch (e) {
      alert("Error loading '" + this.pathName + "/file.json'");
    }
  }
}

推荐阅读