简体   繁体   English

javascript:重试直到承诺解决为止,然后执行

[英]javascript: Retrying until promise is resolved and then execute

I am checking whether some elements of my DOM are fully charged and I wanted to do it through a promise function that checks some elements and if not loaded waits for them. 我正在检查DOM中的某些元素是否已充满电,并且我想通过一个Promise函数来进行检查,该函数会检查某些元素,如果未加载则等待它们。

This is my code 这是我的代码

var jq = jQuery.noConflict();
var df = jq.Deferred();
function keepTrying() {
try{
var el1 = \\element to search for
var success=true
catch(e){
var success= false
}
if (success) {
    //Resolves promises
    df.resolve();
    return df.promise();
} else {
    //Here it retries.. 
    setTimeout(function() {
        keepTrying();
    }, 500);
}
}
keepTrying();
df.done(function() {
//what to do after
});

Do you think there is an easier way to do it? 您认为有更简单的方法可以做到吗? I am working on Qualtrics so importing external libraries could be tricky when passing from one function to another. 我正在研究Qualtrics,因此从一个函数传递到另一个函数时,导入外部库可能会很棘手。

I'd use an inner recursive function, and resolve the promise when the element is found. 我将使用内部递归函数,并在找到元素时解决诺言。
You could add a count to that, and reject the promise after n tries etc. 您可以在其中添加一个计数,并在n次尝试后拒绝承诺。

function keepTrying() {

   var def = $.Deferred();

   (function rec() {
        var el  = document.getElementById('something');
        if ( el === null ) {
            setTimeout(rec, 500);
        } else {
            def.resolve();
        }
   })();
}

keepTrying().done(function() { ... });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM