2015-05-13 41 views
2

我是新來AngularJS $ q和承諾,我瞭解到,如果我用$http.get(),我可以得到一個承諾,我可以chainly使用其.then功能像如何角承諾。於是工作

$http.get(url) 
    .then(function(data){}, function(err){}) 
    .then(function(data){}, function(err){}) 
    ..... 

然後每返回一個新的承諾,但我的問題是我怎麼知道,然後已經解決?我注意到的一件事是,如果我添加返回到function(data){},那麼下一個函數可以從前一個函數獲取返回值,那麼這是否意味着我需要給出返回值作爲解決方案?

回答

0

當第一個then的回調執行時,最初的承諾已經解決,但您可以像您所描述的那樣鏈接thens。 每個then調用創建一個新的衍生承諾。如果您從then回調中返回具體值,則派生的承諾將使用該值進行解析。您將能夠訪問該值作爲參數在隨後的回調then

serviceCall().then(function(){})//nothing returned => resolves with undefined value 
      .then(function(){return 10;})//will resolves with the value 10 
      .then(function(data){//data is 10 here 
       }); 

基本上沒有需要手動解決的承諾。您也可以調用外部函數來返回承諾,如其他$ http請求。

serviceCall().then(function(){ 
    return $http.get('/get-customer-from-server');//returns customer 
}) 
.then(function(customer){ 
    //the customer is available here 
}) 

爲簡潔起見,我省略了錯誤回調。如果任何承諾被拒絕,錯誤回調將執行,這可能是由於某處出現故障導致的。有一個簡短的錯誤處理符號。代替然後用兩個回調可以使用catch

serviceCall().then(function(){ 
}) 
.catch(function(){//error handling if promise was rejected 
}) 

捕撈是.then(null,function(){});

這裏更多信息別名:http://www.syntaxsuccess.com/viewarticle/angular-promise-chaining-explained

1

我怎麼知道那件事已經解決?

正如你注意到,在執行回調後then()返回的承諾得到解決(這是在第一承諾滿足執行)。它確實解決了回調的結果。

我是否需要給予回報以解決問題?

沒有,如果從回調不return什麼,結果是undefined - 就像與普通函數調用。

但是,你實際上有更多的選擇在回調建立一個結果比返回一個普通值:

  • 可以return另一個承諾。由then()返回的承諾將採用它,即以其結果履行或拒絕及其理由一經解決。
  • 你可以throw一個例外。它會被自動捕獲,並由此產生的承諾被拒絕。