jquery - 带有 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 做错了。但我不知道是什么!
解决方案
这可能不是一个直接的答案,但如果您等待您的承诺,那么对您的代码进行推理会更容易。
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'");
}
}
}
推荐阅读
- laravel - 在 php laravel 5.4 中更改日期格式?
- python-3.x - 在 Python 3 中按顺序打开列出的 URL?
- c++ - Eclipse中的Makefile项目可以运行但不能调试,为什么?
- html - 如何在 Jekyll 中按字母顺序对帖子进行排序
- mysql - 向现有表添加外键约束
- reactjs - 在 reactJS 中使用 getusermedia 媒体设备录制音频
- reactjs - 为什么没有通过 react-router 中的链接收到道具
- asp.net-mvc - ValidationMessageFor 在 TryValidateModel 之后不起作用
- javascript - 如何切换多个字体图标
- node.js - Heroku上的Bcrypt无效ELF标头