【发布时间】:2019-12-14 22:19:21
【问题描述】:
我正在使用proxy object,在其中我检测到对象值更改,然后通过 AJAX 加载新内容,我使用setInterval 函数等待 AJAX 请求中的元素存在,然后执行一段代码。我这样做是因为我的情况需要它。我做了一个简短的 sn-p 示例:
var handler = {
makeThings: 0,
otherStuff: 0
};
var globalHandler = new Proxy(handler, {
set: function(obj, prop, value) {
obj[prop] = value
if (prop == "makeThings") {
var clearTimeSearchProxy = setInterval(function() {
if ($("p").length) {
console.log("The element finally exist and we execute code");
clearTimeout(clearTimeSearchProxy);
}
}, 100);
}
return true;
}
});
$(document).ready(function() {
$("button").on("click", function() {
globalHandler.makeThings = 1;
//This element comes with ajax but I use a setTimeout for this example
setTimeout(function() {
$("#newContent").append("<p>Ajax element</p>");
}, 2000);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<button>New content</button>
<div id="newContent"></div>
</body>
现在我想知道如何以更清洁、高效和优雅的方式改进代码。当来自 AJAX 的元素存在于 DOM 中时,我正在考虑使用 promises 而不是 setInterval 来执行代码。
我怎样才能让它工作?我应该在这种情况下使用其他 JavaScript 功能而不是 promises 吗?我坚持实现我所需要的承诺,这是我迄今为止所尝试的。
var handler = {
makeThings: 0,
otherStuff: 0
};
var globalHandler = new Proxy(handler, {
set: function(obj, prop, value) {
obj[prop] = value
if (prop == "makeThings") {
var myFirstPromise = new Promise((resolve, reject) => {
if ($("p").length) {
resolve("Exist");
} else {
reject("It doesnt exist.");
}
});
myFirstPromise.then((data) => {
console.log("Done " + data);
}).catch((reason) => {
console.log("Handle rejected promise: " + reason);
});
}
return true;
}
});
$(document).ready(function() {
$("button").on("click", function() {
globalHandler.makeThings = 1;
//This element comes with ajax but I use a setTimeout for this example
setTimeout(function() {
$("#newContent").append("<p>Ajax element</p>");
}, 2000);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<button>New content</button>
<div id="newContent"></div>
</body>
【问题讨论】:
-
这能回答你的问题吗? How to wait until an element exists?
标签: javascript jquery ecmascript-6 promise es6-promise