简体   繁体   中英

Handling conditional Angular Promises

I want to make some API call if the status is 'ready' and then once only after that resolves I want to execute some statements.

If the status is not ready I don't want to make the API call but will still execute the statements.

I have it done it like this :

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;

I know I am making some bad coding practices here .

I may not need $q.all at all.

But I can't figure out how to handle the situation - because the last 2 lines would be executed

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

How can I effectively write them so that both the situations are handled?

This should work, for lines to execute regardless I recommend trying the .finally block. you can check the job status then call the job details function.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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