return 来自 settimeout 中调用的函数的承诺

return promise from a function called in settimeout

下面的代码给我一个错误,指出 getConfigDetails...then 不是一个函数。如果 isConfigLoaded 变量设置为 true,我想 return 来自函数 getConfigDetails 的承诺,否则继续调用它直到它是。

var getConfigDetails = function () {
    if ($rootScope.isconfigloaded) {
        configDetails.roles = $rootScope.orgConfig.roles.slice();
        configDetails.departments = $rootScope.orgConfig.departments.slice();
        configDetails.levels = $rootScope.orgConfig.levels.slice();
        configDetails.designation = $rootScope.orgConfig.designation.slice();
        return Promise.resolve();
     } else {
        setTimeout(function(){
            getConfigDetails();
        },200);
     }
};

getConfigDetails().then(function(){});

您可以执行以下操作:

var getConfigDetails = new Promise(function(resolve, reject){
  var ticker = setInterval(function(){
    if ($rootScope.isconfigloaded) {
        //the other stuff
        clearInterval(ticker);
        resolve();
    }
  }, 200);
});

你应该可以像getConfigDetails.then(function(){})

那样使用它

注意它不是一个函数,只是一个承诺。如果您真的希望它成为一个函数,请执行以下操作:

function getConfigDetails() {
  return new Promise(function(resolve, reject){
    var ticker = setInterval(function(){
      if ($rootScope.isconfigloaded) {
          //the other stuff
          clearInterval(ticker);
          resolve();
      }
    }, 200);
});