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!