0

This is the service, it use $q and promise to wait for http.jsonp return the data.

var app=angular.module('myModule', ['ngSanitize']);
  app.service('httpq', function ($http, $q)
  {
    return {
      get: function(url) 
      {
         var defferer = $q.defer()
         $http.jsonp(url).success(function (data){
           defferer.resolve(data)
         })
         return defferer.promise
      }
    }

  });

This is the controller, it split comment text at first and use forEach & http calls to find the userid of @username from remote server, then add href like [a href="#/app/userid]@username[/a]

app.controller('HelloCtrl', function($scope, httpq, $http) 
  {
     var items=[];
     var url = 'https://api.instagram.com/v1/media/1059951115357899614_375673057?access_token=242292692.1fb234f.bbbbfc4972fb4bdea524e5c382cd7e48&callback=JSON_CALLBACK';

      httpq.get(url).then(function (data) {

        angular.forEach(data.data.comments.data, function(value, key) {

          var tagslistarr = value.text.split(' ');
          var text='';

          angular.forEach(tagslistarr, function(value2, key2) {

              if(value2.indexOf('@') == 0){
                username = value2.substring(1);
                var url2='https://api.instagram.com/v1/users/search?q='+username+'&count=1&access_token=242292692.1fb234f.bbbbfc4972fb4bdea524e5c382cd7e48&callback=JSON_CALLBACK';

                httpq.get(url2).then(function (data2) {

                  var userid=data2.data[0].id;
                  console.log(username+': ' + userid);
                  value2='<a href="#/event/home/user/'+userid+'/'+username+'">'+value2+'</a>';

                })

              }

              text+=value2+' ';


          });

          console.log('text: ' + text);
          items.push(text);

        });

        $scope.messages = items;

      });

  });

but the controller doesn't wait for the 2nd http calls(url2), here is the code:

httpq.get(url2).then(function (data2) {
  //console.log("data2:"+data2.data[0].id);
  var userid=data2.data[0].id;
  console.log(username+': ' + userid);
  value2='<a href="#/event/home/user/'+userid+'/'+username+'">'+value2+'</a>';
  //console.log('str: ' + value2);
})

Here is the running demo

Any help would be much appreciated. Best Regards.

DinDin
  • 787
  • 1
  • 6
  • 6
  • 3
    Avoid the [deferred antipattern](http://stackoverflow.com/q/23803743/1048572)! – Bergi Sep 17 '15 at 13:53
  • I'm not seeing the error here. In you demo the user ID is changing each time. What make you think it's not waiting for the second get to finish? – Matt Ball Sep 17 '15 at 15:46
  • hello Matt Ball, the console show userid correctly, but the view not update value2 with link tag from httpq.get(url2).then(function (data2) – DinDin Sep 17 '15 at 16:13
  • No time to write full answer - **[try this](http://codepen.io/anon/pen/epzpJp?editors=100)** – Roamer-1888 Sep 20 '15 at 05:34

0 Answers0