【问题标题】:return promise from a function called in settimeout从 settimeout 中调用的函数返回承诺
【发布时间】:2019-04-15 02:05:42
【问题描述】:

以下代码给我一个错误,指出getConfigDetails...then 不是函数。如果isConfigLoaded 变量设置为true,我想从函数getConfigDetails 返回一个promise,否则继续调用它直到它是。

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(){});

【问题讨论】:

  • 改用return $timeout(...),它返回一个Promise。也可以尝试使用$q 服务作为 Promises
  • 从超时做出一个承诺,然后使用then对它的getConfigDetails调用
  • @Bergi 你能举个例子解释一下吗?
  • @ManavChawla new Promise(resolve => setTimeout(resolve, 200)).then(getConfigDetails) 是一个承诺链,你可以return
  • @Bergi 我不确定我是否关注。

标签: javascript angularjs settimeout es6-promise


【解决方案1】:

您可以执行以下操作:

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);
});

【讨论】:

    猜你喜欢
    • 2016-01-11
    • 2017-04-05
    • 2016-10-24
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    相关资源
    最近更新 更多