简体   繁体   中英

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.

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.

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.

function keepTrying() {

   var def = $.Deferred();

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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