2015-11-11 24 views
0

我理解使用'.then'鏈接承諾,但我創建的應用程序仍然不會按順序觸發。鏈接HTTP發佈承諾角度不在序列中

dataFactory.getFirst().then(function(resp3){ 
     //handling of resp 
     console.log('one'); 

    }).then(dataFactory.doSecond(val).then(function(resp) { 
     //handling of resp 
     console.log("two"); 

    })).then(dataFactory.getThird().then(function(resp2) { 
     //handling of resp 
     console.log("three"); 

    })).then(function(){ 
     $state.go('tab.main'); //goes to main page 
    }); 

'dataFactory。'都是我在我的services.js中調用的HTTP Post方法。我明白我沒有包含任何異常/失敗處理,因爲我從頭開始重新編寫了我的整個代碼(非承諾)。一旦我解決了這個問題,我會添加它們。

問題是,'getThird()'值將首先打印在控制檯上,然後是'doSecond()'值,這是我不想要的。任何指導和建議將深受讚賞。

更新:即使考慮'@Jaromanda X'的答案,我仍然無法實現順序鏈接。控制檯不按順序打印「一,二,三」。是否由於服務器響應延遲?

更新的代碼:

var resp; var resp2; var resp3; 

(resp3 =dataFactory.getFirst(valone)) 
.then(function(resp3){ 
    console.log('one'); 
}) 
.then(resp = dataFactory.doSecond(val)) 
.then(function(resp) { 
    //handling of resp 
    console.log("two"); 
}) 
.then(resp2 = dataFactory.getThird(valtwo)) 
.then(function(resp2) { 
    //handling of resp 
    console.log("three"); 
}).then(function(){ 
    $state.go('tab.main'); //goes to main page 
}); 

doSecond(VAL)的所有功能都與此類似,只是不同的地址,返回不同的值:

dataFactory.doSecond= function(val){ 
    var config = { 
     headers: { 
      'Content-Type': 'application/x-www-form-urlencoded' 
     } 
    } 

var data = 'val=' + val; 
var httpAddressdoSecond = "http://"+IPAddress+"/webserviceURL"; 

return $http.post(httpAddressdoSecond, data, config); 

}; 

回答

2

你要做到這一點

dataFactory.getFirst() 
.then(function(resp3){ 
    console.log('one'); 
}) 
.then(dataFactory.doSecond) 
.then(function(resp) { 
    //handling of resp 
    console.log("two"); 
}) 
.then(dataFactory.getThird) 
.then(function(resp2) { 
    //handling of resp 
    console.log("three"); 
}).then(function(){ 
    $state.go('tab.main'); //goes to main page 
}); 

因爲你這樣做的方式,你調用doSecond,立即getThird,而不是由於前面的承諾解決

+0

我會試試看!等一下,謝謝! – Gene

+0

按照你的方法,我的'resp'變得沒有定義,有什麼想法? – Gene

+0

沒有看到'doSecond'和'getThird'函數是什麼,沒有機會 - 我的猜測是'doSecond'實際上並沒有返回任何東西。您的原始代碼沒有與resp做任何事,所以沒有線索 –