如何使用Promises编写我的函数 [英] How to write my function with Promises

查看:93
本文介绍了如何使用Promises编写我的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将HTML(外部应用)加载到 iFrame

I am load HTML (external app) into an iFrame

我想做某事(当元素在我的 iFrame 中可用时, callback )。在这里我是怎么写的,我想用Promises来写这个:

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 with Promises instead:

function doWhenAvailable(selector, callback) {
  console.warn("doWhenAvailable", selector)
  if ($('#myiFrame').contents().find(selector).length) {
      var elt = $('#myiFrame').contents().find(selector);
      console.info("doWhenAvailable Found", elt)
      callback && callback(elt);
  } else {
      setTimeout(function() {
          doWhenAvailable(selector, callback);
      }, 1000);
  }
}

实际上不是使用 setTimeout ,我想使用 setInterval 重复查找元素,直到找到并解决承诺。

Actually instead of using setTimeout, I'd like to use setInterval to repeat the "find element" until it's found and resolve the "promise".

推荐答案

不,你不会使用 setInterval ,你只需将超时包装在一个承诺中并放弃回调:

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

function wait(t) {
    return new Promise(function(resolve) {
        setTimeout(resolve, t);
    });
}
function whenAvailable(selector) {
    var elt = $('#myiFrame').contents().find(selector);
    if (elt.length)
        return Promise.resolve(elt);
    else
        return wait(1000).then(function() {
            return whenAvailable(selector);
        });
}

这篇关于如何使用Promises编写我的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆