javascript - AngularJS looping through http get req to find correct url -


so i'm working on project i'm making http request angular around 1500 urls looking json matches condition have (only 1 of urls match). have implementation work (but isnt deterministic i'm assuming because requests asynchronous although might bug??). i'm still kinda new angular i'm not sure if i'm doing correctly @ i'm open changing code entirely!

this.matchingurl; this.data; this.findurl = function(condition) {   var = this;   (var = 0; <= ; i++) {     // looping through url list     (var = 0; < urllist.length; i++) {       (var j = 0; j < urllist[i]['list'].length; j++) {         this.url = 'http://' + urllist[i]['list'][j] + restofurl;         var tempurl = urllist[i]['list'][j];         $http.get(this.url).success(function(data) {           if (condition met in data) {             that.matchingurl = tempurl;             return;           }         })         .error(function(data){           // error handling         });       }     }   } } 

tldr: matchingurl isn't expect? still goes inside "condition" loop doesn't spit out right url. gives me same "url" sublist, right or wrong.

i suggest use $q promise of angularjs task, either can check 1 url @ time serially( slow if ask me), or results @ time requesting parallely. below, have done crude implementation of latter

this.findurl = function(condition) {     var urls =[], self = this, ourl;   // collect urls     urllist.foreach(function(list){         list.foreach(function(url){             ourl.push(url);             urls.push('http://' + url + restofurl);  // not sure getting restofurl from...         });     });      $q.all(urls.map(function(url){         return $http.get(url);  // returns promise each url, mapping urls promise.     })).then(function(datas){         datas.some(function(data, i){             if(data == condition){  // change per requirement                 self.matchingurl = ourl[i];                 return true;             }         })     }); } 

edit:

same thing done checking 1 url @ time:

this.findurl = function(condition) {     var urls =[], self = this, ourl;   // collect urls     urllist.foreach(function(list){         list.foreach(function(url){             ourl.push(url);             urls.push('http://' + url + restofurl);  // not sure getting restofurl from...         });     });      function check(i){         function fail(){    // move check next url in array             i++;             if(i<urls.length)   return check(i);             console.log('none of urls matching');                         }          return http.get(urls[i]).then(function(data){             if(data == condition){  // change per requirement                 self.matchingurl = ourl[i];             }else{                 fail();             }         }).catch(fail);     }     check(0);   // start chain } 

Comments