2013-04-29 26 views

cevap

51

Evet, bu onun $http hizmet PromiseAPI etrafında inşa edilmiştir beri angularjs tarafından çok zarif ele alınır. then yöntemi kullanarak kolayca $http yöntemleri bir söz dönmek ve zincir vaat can için Temelde, çağırır. İşte bir örnek:

$http.get('http://host.com/first') 
    .then(function(result){ 
    //post-process results and return 
    return myPostProcess1(result.data); 
    }) 
    .then(function(resultOfPostProcessing){ 
    return $http.get('http://host.com/second'); 
    }) 
    .then(function(result){ 
    //post-process results of the second call and return 
    return myPostProcess2(result.data); 
    }) 
    .then(function(result){ 
     //do something where the last call finished 
    }); 

Ayrıca hem sonradan işleme ve sonraki $http işlevini birleştirebilir, hepsi sonuç ilgilenen kim olduğuna bağlı.

$http.get('http://host.com/first') 
    .then(function(result){ 
    //post-process results and return promise from the next call 
    myPostProcess1(result.data); 
    return $http.get('http://host.com/second'); 
    }) 
    .then(function(secondCallResult){ 
    //do something where the second (and the last) call finished 
    }); 
+3

Teşekkürler Pawel, ben kontrol edeceğim. Şu anda, $ q.all'ı kullandım ve istediğimi yapıyor gibi görünüyor. Ama bunu da deneyeceğim. – Ketan

+11

@Ketan 'q.all' ve burada açıklanan çözüm 2 farklı şeydir. "q.all" harikadır, ancak yalnızca paralel talepler için çalışır, yani eğer onların emrini önemsemezseniz ve bir istek başka birinin sonuçlarına bağlı değildir. Sorunuzda, bir isteğin bitirilmesi gereken istekleri zincirleme sonrasında olduğunuzu anladım, sonuçları incelemek/işlemek ve daha sonra başka bir istek vermek istiyorsunuz. –

+0

o paralel olarak onları çalıştırmak için Tamam oldu benim özel problemde çıkıyor ama benim asıl istediğim hepsini bitince bazı kod çalıştırmasına oldu. Ancak cevabınız yine de değerlidir çünkü eminim ki bu konuya daha geç ulaşacağım. Cevabını kabul edeceğim. – Ketan

8

Kabul edilen cevap iyidir, ancak bu, krema üzerine gerçekten krema koyan yakalama ve son yöntemleri açıklamamaktadır. Bu great article on promises beni doğru yönlendirdi. İşte bu makaleye dayanan bazı örnek kodlar:

$scope.spinner.start(); 

$http.get('/whatever/123456') 
    .then(function(response) { 
    $scope.object1 = response.data; 
    return $http.get('/something_else/?' + $scope.object1.property1); 
    }) 
    .then(function(response) { 
    $scope.object2 = response.data; 
    if ($scope.object2.property88 == "a bad value") 
     throw "Oh no! Something failed!"; 
    return $http.get('/a_third_thing/654321'); 
    }) 
    .then(function(response) { 
    $scope.object3 = response.data; 
    }) 
    .catch(function(error) { 
    // this catches errors from the $http calls as well as from the explicit throw 
    console.log("An error occured: " + error); 
    }) 
    .finally(function() { 
    $scope.spinner.stop(); 
    });