Search code examples
javascriptxmlhttprequest

Javascript call function after multiple XMLHttpRequests


I have some divs that I replace with new html. So far so good.

(function() { 

  var obj = function(div) {     

    var obj = {};
    obj.divToReplace = div;
    obj.objId = obj.divToReplace.dataset.id;

    obj.template = "<div class="newDivs"><p>@Name</p><img src='@ImageUrl'/></div>";

    obj.replaceDiv = function() {
        var xhr = new XMLHttpRequest();
        xhr.open( 'GET', encodeURI('http://.../' + obj.objId) );
        xhr.onload = function(e) {
            if (xhr.status === 200) {
                var x = JSON.parse(xhr.responseText).data.attributes;

                var newHtml = obj.template
                            .replaceAll("@Name", x.name)
                            .replaceAll("@ImageUrl", x.imageUrl);

                obj.divToReplace.outerHTML = newHtml;
            }
            else {
                console.log(xhr.status);
            }
        };
        xhr.send();

    };

    return {
        replaceDiv: obj.replaceDiv
    }

};

String.prototype.replaceAll = function(search, replace)
{
    return this.replace(new RegExp(search, 'g'), replace);
};

//get the elements I want to replace
var elems = document.getElementsByClassName('divToReplace');

//replace them
for (i = 0; i < elems.length; i++) { 
    obj(elems[i]).replaceDiv();
}

//call handleStuff ?


})();

Then I want to add addEventListener to the divs, and it's here I get stuck. I want to call handleStuff() after all the divs are replaced. (Because of course, before I replace them the new divs don't exists.) And I can't use jQuery.

 var handleStuff = function(){

   var classname = document.getElementsByClassName("newDivs");

   var myFunction = function() {

   };

   for (var i = 0; i < classname.length; i++) {
       classname[i].addEventListener('click', myFunction, false);
   }
   ...............

How can I add a callback that tells me when all the divs are replaced? Or is it overall not a good solution for what I'm trying to do?


Solution

  • Sorry for using jQuery previously, here is solution with native Promise(tested)

    (function() {
    
      var f = {
        send : function(){
            var promise = new Promise(function(resolve, reject){
                var xhr = new XMLHttpRequest();
                xhr.open( 'GET', encodeURI('http://www.google.com/') );
                xhr.onload = function(e) {
                    if (xhr.status === 200) {
                        //your code
                        resolve();
                        console.log('resolve');
                    } else {
                        console.log(xhr.status);
                    }
                };
                xhr.send();
            });
            return promise;
        }
      }
    
      var promises = [];
      for (i = 0; i < 100; i++) { 
          promises.push(f.send());
      }
    
      Promise.all(promises).then(function(){
          console.log('success');
      });
    })();