然后在返回承诺后不调用函数

Then function isn't called after returning a promise

我创建了一个函数来检查元素是否已经存在,如果不重复该函数直到它存在:

function waitForElementToDisplay(selector) {
    return new Promise(function (resolve, reject) {
        if (document.querySelector(selector) != null) {
            console.log('Element is displayed now');
            resolve();
        } else {
            setTimeout(function () {
                waitForElementToDisplay(selector, 500);
            }, 500);
        }
    })
}

我在Shepherd.js的beforeShowPromise函数中使用了这个函数。此函数让包等待进入下一个巡回步骤,直到承诺得到解决。 beforeShowPromise 函数如下所示:

beforeShowPromise: function () {
    return new Promise(async function (resolve) {

        const selector = '.exampleTemplates';

        await waitForElementToDisplay(selector).then(() => {
            console.log('Do something');
        }).catch(err => {
            console.log(err);
        });
    })
},

我想等到waitForElementToDisplay功能解决了,这样Shepherd的功能就可以解决了。但是,正在调用 .then.catch 函数。有人可以向我解释为什么它不起作用吗?

Promise 仅在元素存在时才解析。

如果没有,您将进入递归调用该函数的 else 分支。这会创建一个 new promise,但是当 that 解决时你永远不会做任何事情。最初的承诺被搁置了。

您可以用新的承诺解决原来的承诺:

resolve( waitForElementToDisplay(selector) );

您需要将 resolve 传递给递归调用:

const checkIfElementExists = (resolve, selector) => {
  if (document.querySelector(selector) !== null) {
    console.log('Element is displayed now');
    resolve();
  } else {
    setTimeout(checkIfElementExists, 500, resolve, selector);
  }
};

function waitForElementToDisplay(selector) {
  return new Promise(function(resolve) {
    checkIfElementExists(resolve, selector);
  })
}

或者,封装在waitForElementToDisplay里面:

function waitForElementToDisplay(selector) {
  return new Promise(function(resolve) {
    (function checkIfElementExists() {
      if (document.querySelector(selector) !== null) {
        console.log('Element is displayed now');
        resolve();
      } else {
        setTimeout(checkIfElementExists, 500);
      }
    })();
  })
}