3

I am having a very hard time getting this script to run in syncro...

What I am trying to acomplish is: 1. start Each loop that iterates over array of urls 2. Use value in Get request that loads the html of the url into new variable (same domain, this part works just fine). 3. Place that variable (the html from url) in div as .html(var); 4. Next in loop 5. When loop is finished console.log("Finished"

Here is my code:

var deferreds = [],
    ids = ['/node/add/1000-books','/node/add/3d','/node/add/merci-staff-rooms','/node/add/about','/node/add/attend','/node/add/banner','/node/add/blogs-ahml','/node/add/book'],
    users = [];

    $.each(ids, function(i,v){
        deferreds.push(
                $.get("http://www.ahml.info"+v, function( data ) {
                    $(".tohere").append(data);
                        console.log("Loaded "+v);
                    });
        );
    });

    $.when($, deferreds).done(function(){
        console.log("Should be end");
    });
})

The $.when does fire after all console.logs have finished, so I know some scyncronisity is working here, but the script is still appending..

How do I modify so that $.when does not fire until .get requests have finished?

I have tried placing

var newdeff = $.Deferred();

&

newdeff .resolve();

within the each function but to no avail..

Thank you

Jason
  • 396
  • 4
  • 19

1 Answers1

0

You have the wrong syntax, it should be

$.when.apply($, deferreds).done(function(){
    console.log("Should be end");
});

You'll need to use apply() to pass in an array of promises, otherwise it just resolves right away, as you're passing jQuery, which is not async, to $.when

adeneo
  • 312,895
  • 29
  • 395
  • 388