2017-06-28 67 views
0

如果狀態爲「準備就緒」,我想進行一些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.

我怎樣纔能有效地寫出來,這樣既情況的處理方式?

+0

您需要一個包含最後2行的else塊。 –

+0

@DeepthiS我想讓他們執行if塊也。 – StrugglingCoder

回答

0

這應該工作,線路執行,無論我建議嘗試.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; 
} 
+0

狀態未準備好會發生什麼?它永遠不會被調用。我的意思是getJobDetails方法。 – StrugglingCoder

+0

是正確的,如果沒有準備好,那麼它永遠不會被調用。 – alphapilgrim

+0

我也想打電話。只是它會立即被稱爲不在承諾之內。 – StrugglingCoder