2017-06-28 68 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