gpt4 book ai didi

jquery - Typescript Promise with JQuery 似乎运行了两次?

转载 作者:搜寻专家 更新时间:2023-10-30 21:46:42 24 4
gpt4 key购买 nike

我以为我正在慢慢掌握 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");
});

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

最佳答案

这可能不是一个直接的答案,但如果你等待你的 promise ,它会更容易推理你的代码。

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'");
}
}
}

关于jquery - Typescript Promise with JQuery 似乎运行了两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53876560/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com