我了解使用“.then”来链接 promise ,但我正在创建的应用程序仍然不会按顺序触发。
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
});
“数据工厂”。我的所有 HTTP Post 方法都是在 services.js 中调用的。我确实明白我没有包含任何异常/失败处理,因为我从头开始重新编码了我的整个代码(非 promise )。一旦解决了这个问题,我就会添加它们。
问题是有时,“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);
};
最佳答案
你会想要这样做
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,而不是作为先前 promise 解决的结果
关于javascript - 链接 HTTP post promise Angular 不按顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33647708/