簡體   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