繁体   English   中英

处理条件性角度承诺

[英]Handling conditional Angular Promises

如果状态为“就绪”,我想进行一些API调用,然后在解决之后才执行一次我想执行一些语句。

如果状态尚未ready我不想进行API调用,但仍会执行语句。

我这样做是这样的:

if(job.status === 'ready')
    //Makes a promise to fetch the progress API details for ready batches only
    var promise = HttpWrapper.send('/api/jobs/'+job.job_id+'/getDetails', { "operation": 'GET' });

//Once the promise is resolved, proceed with rest of the items
$q.all([promise])
.then(function(result) {
    //Because for not ready batches promise object and it's response wuld be undefined
    if(result[0] !== undefined){
        //Create a property that would hold the progress detail for ready batches
        job.pct = result[0].pct;
    }

    //Want to execute these lines no matter what
    vm.job = job;
    vm.loading = false;

我知道我在这里做一些不好的编码实践。

我可能根本不需要$q.all

但我不知道如何处理这种情况-因为将执行最后两行

For ready batches within then only after that promise resolves, but for other batches there is no promise. So they can get executed quickly.

如何有效地编写它们,以便同时处理两种情况?

无论我建议尝试使用.finally块,这都应该起作用,以便使行执行。 您可以检查作业状态,然后调用作业详细信息功能。

if (job.status === 'ready') {
  getJobDetails(job);
} else {
  defaults(job);
}

function getJobDetails(job) {
  return $http.get('/api/jobs/' + job.job_id + '/getDetails')
    .then(function(resp) {
      if (resp) {
        job.pct = result[0].pct;
      }
    })
    .catch(funcition(error) {
      console.log(error);
    })
    .finally(function() {
      vm.job = job;
      vm.loading = false;
    });
}

function defaults(job) {
  vm.job = job;
  vm.loading = false;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM