What i am doing is chaining various asynchronous tasks that depend on the response of the previous ones to finally get an Array of objects that wrap all the responses to be used in the $scope
. I am using Angular
and MongoDB
.
So, i have multiple Url
that are associated to a specific User
using UserUrl
models. Each Url
is as well associated to a Group
using GroupUrl
models. The client will see a list of Groups
but every item in the list shows data of UserUrl
and the GroupUrl
belonging to each Group
.
For this i am using promises
and a Broadcast Service
.
First i get all the UserUrls
:
allUrlByUser( $scope.user )
.then( function(userUrls){
angular.forEach( userUrls, function(userUrl){
allUrlById(userUrl);
});
});
Foreach Userurl
i resolve the Url
itself:
allUrlById = function( userUrl )
{
return ajaxService
.api( 'allUrlById',userUrl.url )
.then( function( url )
{
var wrap = {
url : url[0],
userUrl: userUrl
};
/*
Emit message passing a object response built
using previous and current async data.
*/
Messenger.call(Messenger.allUrlById,
wrap);
});
The observer of the emitted message is:
$scope.$on(Messenger.allUrlById, function(e,msg) {
return allGroupUrlById(msg);
});
And the callback function is:
allGroupUrlById = function( msg )
{
return ajaxService
.api( 'allGroupUrlById', msg.response.url._id )
.then( function( groupUrl )
{
var wrap = {
url : msg.response.url,
userUrl: msg.response.userUrl,
group : groupUrl[0].group
};
$scope.groups.push(wrap);
});
}
Taking into account i need a final array of wrapped objects mixing data of multiple asynchronous tasks:
You don't need Broadcast Service, promise is enough:
allUrlByUser( $scope.user ).then(function(userUrls){
angular.forEach( userUrls, function(userUrl){
allUrlById(userUrl).then(function(result) {
allGroupUrlById(result);
});
});
});
allUrlById = function( userUrl ) {
return ajaxService
.api( 'allUrlById',userUrl.url )
.then( function( url ) {
return {
url : url[0],
userUrl: userUrl
};
});
}
allGroupUrlById = function(result) {
return ajaxService
.api( 'allGroupUrlById', result.url._id )
.then( function( groupUrl ) {
var wrap = {
url : result.url,
userUrl: result.userUrl,
group : groupUrl[0].group
};
$scope.groups.push(wrap);
});
}