Why does it seem like Typescript Promise with JQuery is executing twice?

Figuring out Promises in Typescript/JS seemed to be going well for me, but I've hit a roadblock.

I've set up Promises to wait for two JQuery getJSON requests to finish. In my browser, when connecting to a local server, everything functions as expected. However, a user provided a HAR log showing that the getJSON requests are being duplicated and the Promise is resolving twice. Strangely, I can't replicate this issue, but it's consistently happening for them using Chrome 71 with plugins disabled.

My anticipated console output should look like this...

   Document Ready
   File Loaded
   Query Loaded
   Got file and query

But on their machine, it looks more like this

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

Below is the slightly simplified code snippet.

class Panel {
  private pathName: string;

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

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

    // begin running 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");
  });

My hunch is that there might be an issue with how I'm handling Promises, possibly only triggered by network timing conditions on the user's machine. But, I'm completely stumped about what exactly that could be!

Answer №1

This might not be the exact solution you're looking for, but consider using async/await to make your code more readable and easier to understand.

class Panel {
  private pathName: string;

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

      // Make API query
      let queryP = await $.getJSON('/api/query');
      this.processQueryResult(queryP);
    } catch (e) {
      alert("Error loading '" + this.pathName + "/file.json'");
    }
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on how to target an iframe upon being shown using Fancybox3

One way to navigate within an iframe is by using the command instance.focus() and then pressing the "right" key on the keyboard. This allows for easier navigation without having to click on a specific button or point inside the iframe. However, this metho ...

Error: The function $(...).maxlength is not recognized - error in the maxlength plugin counter

I have been attempting to implement the JQuery maxlength() function in a <textarea>, but I keep encountering an error in the firefox console. This is the code snippet: <script type="text/JavaScript"> $(function () { // some jquery ...

What is the best way to send a request using an API key through a form submission method?

I encountered an issue while attempting to retrieve the json response through a form using the post method; I kept receiving a forbidden 403 error. window.onload = function() { document.getElementById("Save").onclick = function fun() { var x = docum ...

The marriage of Vue 2.0 and Rails 5: Shifting from Reactive to Declarative Rendering

As I make my way through the Vue guide with a Rails 5 app, I've noticed that although I am able to update my Vue js object, the DOM doesn't behave as described in the Declarative Rendering section. The data and the DOM are supposed to be linke ...

Troubleshooting problem with JQuery autocomplete display

I've come across this question multiple times, but I just can't seem to crack it. I'm using a remote source to retrieve JSON data and while I can see the data in the console, I'm struggling to get it to output. What I really need is for ...

TypeORM - Establishing dual Foreign Keys within a single table that point to the identical Primary Key

Currently, I am working with TypeORM 0.3.10 on a project that uses Postgres. One issue I encountered is while trying to generate and execute a Migration using ts-node-commonjs. The problem arises when two Foreign Keys within the same table are referencing ...

Tips for retrieving an object from an array with Angular and Firestore

Currently, I am attempting to retrieve an object from Firestore using the uid so that I can return a specific object as a value. I have implemented a function in order to obtain the object 'Banana'. getFruit(fruitUid: string, basketUid: string) ...

When logging `self`, the output field is present; however, attempting to log `self.output` results in

I've encountered a strange issue. When I use console.log(self) to log the variable, it shows that the output key is set and contains all the values. However, if I try to log console.log(self.output), it returns undefined. Does anyone know why this is ...

The resolve.alias feature in webpack is not working properly for third-party modules

Currently, I am facing an issue trying to integrate npm's ng2-prism with angular2-seed. The problem arises when importing angular2/http, which has recently been moved under @angular. Even though I expected webpack's configuration aliases to hand ...

Top approach for inserting Class instance into a group

I need some guidance on how to approach this issue. I am interested in creating a set of objects similar to the example below: Person P = new Person(); P.Name = 'John'; P.Surname = 'Dough'; var People = []; People.push(P); Can this b ...

Obtaining a response in string format using the $.ajax function

var module = (function(){ return{ loadData: function(url, success, error){ $.when($.ajax({ type: 'GET', cache: false, url: url, contentType: 'application ...

Encountering error TS2307: Module 'redux' not found when trying to implement redux in Angular 7

Currently, I am diving into the world of Redux and attempting to integrate it into my Angular 7 project using ng2-redux. However, upon visiting the npm page, I discovered that the recommended approach was to install it with npm install @angular-redux/store ...

Having trouble setting the selected option for a select element using the $get method in jQuery?

I'm struggling with setting the selected value of a select option using AJAX, particularly the $get function of jQuery. I've been trying to make it work, but for some reason, setting the textbox is successful while setting the select option isn&a ...

Tips on getting the Jquery .load() function to trigger just once and executing an Ajax request only once

Upon loading the page, I am utilizing the JQuery .load() function to retrieve content from a PHP file. The content loads successfully but it keeps reloading continuously as observed through Chrome Developer tools. I only want the content to load once. var ...

What are the best strategies for creating HTML website designs that are both scalable, adaptable, and versatile?

As a beginner in HTML website design, I have recently started using HTML, CSS, jQuery, and JavaScript for designing websites. After creating a site with almost forty webpages, the client requirements are changing, requiring changes to be made across all ...

What is the best approach to incorporate a stopwatch?

I'm exploring ways to track the time it takes for a user to click a button. While I have a working solution, I'm curious if there's a more efficient method available. Below is my current implementation: export class MainComponent implements ...

Continuously update scrolling functionality

Could you please provide more information about the solution mentioned in the following question? I am facing a similar issue. jQuery’s css() lags when applied on scroll event Regarding solution #3 ->> To ensure continuous updates, it is suggeste ...

Click here to open in a new tab and experience the ever-changing dynamic

Imagine a scenario where a property site displays the main viewed property ad at the top, with smaller ads in square divs below. When a user clicks on one of the smaller ads, it dynamically swaps places with the main ad thanks to JavaScript. All ad data is ...

Encountered an issue in GoJS with Angular 4: ERROR TypeError: Unable to access property 'class' of null at Function.F.fromJson.F.fromJSON

I have just started exploring GoJS and decided to create a sample project by utilizing the Kanban sample available on the GoJs website. I attempted to use Angular and Typescript for this, but encountered an error. AppComponent.html:1 ERROR TypeError: Cann ...

Use JavaScript regex to replace a string only if its length exceeds a certain specified limit

My current approach involves using JavaScript regex to insert an HTML markup for all identified URLs: var exp = /(((|www\.|(http|https|ftp|news|file)+\:\/\/)[&#95;.a-z0-9-]+\.[a-z0-9\/&#95;:@=.+?,##%&~-]*[^.|&bso ...