app.factory('documentListFactory',['$http','$q',function($http,$q){
//申明一个延迟
var deferred = $q.defer();
$http.get('http://3.cs/index.php?_json=1&_content=1').success(function(response){
deferred.resolve(response);
}).error(function(response){
deferred.reject(response);
});
// 返回承诺,这里并不是最终数据,而是访问最终数据的API
return deferred.promise;
}]);
app.factory('documentTagsFactory',['$http','$q',function($http,$q){
//申明一个延迟
return {
query(ids)
{
var deferred = $q.defer();
$http.post('http://3.cs/index.php/tags/assoc-tags',{
'id':ids ? ids : [1,23],
'model':'Document'
}).success(function(response){
deferred.resolve(response);
}).error(function(response){
deferred.reject(response);
});
return deferred.promise;
}
}
}]);
app.controller('listController',['$scope','$http','$q','documentListFactory','documentTagsFactory',function($scope,$http,$q,documentListFactory,documentTagsFactory){
var documentList = {};
/*
code.....
*/
//var promise = $q.all([documentListFactory,documentTagsFactory.query(documentListFactory)]);
promise.then(function(data){
//console.log(data);
//console.log(documentList);
//console.log(3);
});
}]);
As shown in the above code, I use deferred delay for two facotry, and use promise to perform similar synchronous loading.
But now there is a problem
The method query(ids) in my documentTagsFactory requires a parameters are passed, and this parameter depends on Relying on the result of documentListFactory,
I am new to angularjs, but I don’t know how to implement it here. I use $q.all to achieve multiple synchronizations, but I still can’t pass parameters. I wonder if you have any methods,
PS: I really don’t like
$.get(function(){
$.get(function(){
})
})
or
promise.then(function(){
promise2.then(function(){
})
})
This kind of nesting.
What I want is a synchronization-like and non-nested method, thank you
http://stackoverflow.com/questions/24402911/abort-angularjs-http-request-deeply-nested-in-multiple-service-calls
The result returned by $http execution is a promise. What does it mean if you encapsulate it again?
Wouldn’t it be over if I just write it like this
I can understand avoiding callback hell, but the usage of promise is nested, so you have to write it like this even if you don’t like it! If you want to write synchronization, use ES6’s Generetor or ES7’s async
Use
$q.when
methodhttp://jsfiddle.net/hjzheng/nd1wfkj3/