closures - AngularJS nesting promises issues -
i need solve problem , in fact, i'm don'yet understand how retrieve promise result in nesting promise, bellow code
// service mainapp.factory('myservice', ['cmismanager', '$q', 'servicecmis', function(cmismanager, $q, servicecmis) { get_detailfold: function(_objectid){ return servicecmis.getdocumentproperties(_objectid) .then(function(data){ var items = [] ; var imgliste = data.succinctproperties['tsi:image_liste'].split(';') ; (function(imgliste){ (var i=0; i<imgliste.length; i++) { (function(index){ var item = {} ; item.id = imgliste[index] ; return servicecmis.getdocumentproperties(imgliste[index]) .then(function(data){ var contentstreamid = data.succinctproperties['cmis:contentstreamid'] ; return servicecmis.getcontentstreamdocumenturl(data[index], contentstreamid) .then(function(data){ item.urlthumbnail = data ; item.urldetail = data ; items.push(item) ; }) }) })(i) ; } return items ; })(imgliste) ; }) .then(null, function(error){ return error; }) ; } }; }]) }]) // controleur myservice.get_detailfold(41946).then(function(data){ $scope.datatest = data ; }) ;
i expected result this
[ {"id":1, "urlthumbnail":"./img/test/1.jpg", "urldetail":"./img/test/1.jpg"}, {"id":2, "urlthumbnail":"./img/test/2.jpg", "urldetail":"./img/test/2.jpg"}, {"id":3, "urlthumbnail":"./img/test/3.jpg", "urldetail":"./img/test/3.jpg"}, {"id":4, "urlthumbnail":"./img/test/4.jpg", "urldetail":"./img/test/4.jpg"}, {"id":5, "urlthumbnail":"./img/test/5.jpg", "urldetail":"./img/test/5.jpg"} ]
but instead, i've got undefined
thanks in advance help
you should utilize .map
, .foreach
loops in order avoid nasty closures around loops.
that said, problem rather simple, you're returning inside closure rather ouside of it.
return items ; })(imgliste) ;
returns anonymous invoked function closure, instead starters do:
})(imgliste) ; return items ;
however, you're still not populating items in right order since won't wait them - utilize $q.all
waits array of promises. code should like:
mainapp.factory('myservice', ['cmismanager', '$q', 'servicecmis', function(cmismanager, $q, servicecmis) { //... get_detailfold: function(_objectid){ return servicecmis.getdocumentproperties(_objectid).then(function(data){ var items = [] ; var imglist = data.succinctproperties['tsi:image_liste'].split(';'); var ps = imgliste.map(function(img){ return servicecmis.getdocumentproperties(img).then(function(properties){ var contentstreamid = data.succinctproperties['cmis:contentstreamid']; return servicecmis.getcontentstreamdocumenturl(img, contentstreamid); }).then(function(data){ return { id:img, urlthumbnail: data, urldetail: data }; }); }); return $q.all(ps); // waits promises resolve }); // don't .catch here, let other side handle failures } }]);
Comments
Post a Comment