【发布时间】:2021-06-23 00:13:45
【问题描述】:
由于异步Ajax调用我们使用promise,所以其他等待Ajax成功对象的JS可以访问其更新的属性。
我们有 300 个 JS 会调用这个 promise,如果有这么多 JS 调用 promise,我们是否有任何限制,它可能会开始挂起或永远不会解决。
请指教
提前致谢
(function () {
window.myObject = window.myObject || {};
let isProfileUpdated = false;
myObject.waitforProfile = new Promise(function (resolve, reject) {
let maxTry = 50;
let currentTry = 0;
let tryForProfile = function () {
if (currentTry < maxTry && isProfileUpdated) {
resolve();
} else if (currentTry < maxTry) {
currentTry++;
setTimeout(tryForProfile, 350);
}
else {
reject('profile never resolved');
}
}
tryForProfile();
});
$.ajax({
url: 'www.google.com',
async: true,
success: function (result) {
result = result.model;
if (result != undefined) {
window.myObject.title = result.title
isProfileUpdated = true;
}
}
});
})();
调用者 - 我们有很多调用者依赖于 MyObject 属性
function initalizeNavigation() {
if (myObject.title !== "") {
createAuthenicatedUtilityNav();
} else {
createSignedOutUtilityNav();
}
}
myObject.waitforProfile(initalizeNavigation)
.catch(function (message) {
console.log(message)
});
【问题讨论】:
-
你不能称之为承诺。您的意思是代码中的 300 个点在进行相同的 Ajax 调用,将
then侦听器添加到单个承诺(或await承诺)或其他什么?请在帖子中分享一些代码示例并附上解释。 -
@traktor 更新了我的问题,希望对您有所帮助
标签: javascript jquery promise