Skip to content Skip to sidebar Skip to footer

How To Write My Function With Promises

I am load HTML (external app) into an iFrame I want to 'do' something (callback) when an element becomes available in my iFrame. Here how I wrote it, and I'd like to write this wit

Solution 1:

No, you would not use setInterval, you just would wrap the timeout in a promise and drop the callback:

functionwait(t) {
    returnnewPromise(function(resolve) {
        setTimeout(resolve, t);
    });
}
functionwhenAvailable(selector) {
    var elt = $('#myiFrame').contents().find(selector);
    if (elt.length)
        returnPromise.resolve(elt);
    elsereturnwait(1000).then(function() {
            returnwhenAvailable(selector);
        });
}

Solution 2:

Keeping your recursive style, it would have become something like that :

functiondoWhenAvailable(selector) {
  var dfd = jQuery.Deferred();
  console.warn("doWhenAvailable", selector)
  if ($('#myiFrame').contents().find(selector).length) {
      var elt = $('#myiFrame').contents().find(selector);
      console.info("doWhenAvailable Found", elt)
      return dfd.resolve(elt);
  } else {
      setTimeout(function() {
          doWhenAvailable(selector).then(function(e) {
            dfd.resolve(e);
          });
      }, config[env].wrapper.timeOutInMs);
  }
  return dfd.promise();
}

But I would have tried to avoid recursive calls here

Solution 3:

The general idea is to return a promise instead of receiving a callback.

Example:

var xpto = function(res) {
    returnnewPromise((resolve, reject) => {
        if(res > 0) resolve('Is greater');
        elsereject(newError('is lower'));
    });
}

So in your case:

functiondoWhenAvailable(selector) {

  functionwork(callback) {
     if ($('#myiFrame').contents().find(selector).length) {
       var elt = $('#myiFrame').contents().find(selector);
       console.info("doWhenAvailable Found", elt)
       callback(elt);
    }
  }

  returnnewPromise((resolve, reject) => {
    console.warn("doWhenAvailable", selector)
    setInterval(() =>work(resolve), 1000);
  })
}

Solution 4:

Here:

functiondoWhenAvailable(selector) {
    returnnewPromise(function(resolve, reject){

console.warn("doWhenAvailable", selector)
  if ($('#myiFrame').contents().find(selector).length) {
      var elt = $('#myiFrame').contents().find(selector);
      console.info("doWhenAvailable Found", elt)
      resolve(elt);
  } else {
      setTimeout(function() {
          doWhenAvailable(selector).then(function(data){
  resolve(data);
});
      }, config[env].wrapper.timeOutInMs);
  }

    }
}

And call your function like that:

doWhenAvailable("#elemId").then(function(elt){
//do what you want
});

Post a Comment for "How To Write My Function With Promises"