Promise resolve/reject 立即评估,即使它应该等待另一个 promise?

Promise resolve/reject evaluating instantly even though it should be waiting for another promise?

我正在使用一系列承诺来维护正确的操作顺序,以便我可以加载一些数据,并在 app/page 加载之前初始化一些对象。

在使我的代码更加模块化以便我可以重用一些函数的过程中,我似乎超越了我对 promises 的理解,我发现 .then initApp() 之后的链从未执行过 - 承诺只是 resolved/rejected 立即。

我的 getData 函数完美运行:

function getData(promises, callback) {
  let getDataComplete = new Promise(function (resolve, reject) {
    Promise.all(promises)
      .then(function () {
        if (callback && typeof callback === "function") {
          debug_log("getData: running callback");
          callback();
        }
        return resolve;
      })
      .catch(function (error) {
        return reject;
      });
  });
  return getDataComplete;
}

但是下面的部分(执行它的部分)没有等待它完成?

const initApp = new Promise((resolve, reject) => {
  let dataReturned = getData([
    getPartners,
    getProducts,
    getCurrencies,
    getSites
  ]);
  if (dataReturned == resolve) {
    debug_log("resolve initapp")
    resolve;
  } else {
    debug_log("reject initapp")
    reject;
  }
});

initApp
  .then(() => {
    initJSComponents();
  })
  .catch((error) => {
    debug_log("Problem during js component initialisation.", error);
  })
  .then(() => {
    initDOM();
  })
  .then(function () {
    //some more stuff here
  })
  .catch((error) => {
    debug_log("Problem during initialisation.", error);
  });

有什么想法吗?我被难住了,几个小时以来我一直在查看和重写它。

您的 getData 函数返回 Promise,但您在执行后没有使用 Promise#thenPromise#catch 方法。因此,在调用此函数后,您无需等待即可立即获得 Promise 对象。您可能应该像这样更改 initApp 函数:

const initApp = new Promise((resolve, reject) => {
  getData([
    getPartners,
    getProducts,
    getCurrencies,
    getSites
  ]).then(() => {
    debug_log("resolve initapp")
    resolve();
  }).catch(() => {
    debug_log("reject initapp")
    reject();
  });
});

只有在 getData 函数返回的 Promise 得到解析(或拒绝)后,您的 initApp 才会解析(或拒绝)他的 Promise

function getData(promises, callback) {
  return new Promise(function (resolve, reject) {
    Promise.all(promises)
      .then(function () {
        if (callback && typeof callback === "function") {
          debug_log("getData: running callback");
          callback();
        }
        resolve();
      })
      .catch(function (error) {
        reject();
      });
  });
}

const initApp = new Promise((resolve, reject) => {
  getData([
    getPartners,
    getProducts,
    getCurrencies,
    getSites
  ]).then(allFine => {
      resolve();
  }, somethingWrong => {
      reject();
  });
});

initApp
  .then(() => {
    initJSComponents();
  })
  .catch((error) => {
    debug_log("Problem during js component initialisation.", error);
  })
  .then(() => {
    initDOM();
  })
  .then(function () {
    //some more stuff here
  })
  .catch((error) => {
    debug_log("Problem during initialisation.", error);
  });