2

The goal: loop through an array of urls ONE AT A TIME, letting them load completely using postMessage to determine when finished (some of the pages will take a long time)

Implemented this, but it's not working quite right: jquery deferred in for loop

Implemented this, and it's working, but not in a loop because the javascript only opens the last window: http://davidwalsh.name/window-postmessage

function scrape(url){
    var deferred = new $.Deferred();
      var myPopUp = window.open(url,'myWindow');
      setInterval(function(){
        var message = 'Hello!  The time is: ' + (new Date().getTime());
        console.log('Scraper Launcher:  sending message:  ' + message);
        myPopUp.postMessage(message,domain);//send the message and target URI
        },6000);

        //listen to holla back
        window.addEventListener('message',function(event) {
                if(event.origin !== domain) return;
                console.log('received response:  ',event.data);
                if(event.data == 'You were successful!'){
                   console.log('closing child window');
                   myPopUp.close();
                   deferred.resolve('Success');
                }else{
                   console.log('oh dear, FAILURE: ' + urls[i]);
                   deferred.resolve('Failure');
                }
             },false);


    return deferred.promise();
}

    var urls = [domain +"/url1",domain +"/url2"];

   $("#launch_windows").click(function(){
      console.log('launching');
      for (i = 0; i < urls.length; i++) {
         (function(i){
            console.log('NOW i is ' + i + ' and url is ' + urls[i]);
            $.when(scrape(urls[i])).then(function(results){
               console.log('DONE (' + results + ')with ' + urls[i]);
            });
          })(i);
      }
    });

And if this is totally horrible logic and code, I'm all ears for suggestions.

1 Answer 1

9

I like to solve these problems (sequential loops of async operations) by creating a resolved $.Deferred, adding to the chain, and assigning the value of that deferred to the new promise with each iteration.

$("#launch_windows").click(function(){
    console.log("launching");
    var dfd = $.Deferred().resolve();
    for(i = 0; i < urls.length; i++){
        (function(i){
            dfd = dfd.then(function(){
                return scrape(urls[i]);
            }).then(function(results){
                console.log("results: "+results);
            });
        })(i);
    }
});

Cleaner version with a forEach instead of IIFE to provide closure:

var dfd = $.Deferred().resolve();
urls.forEach(function(url){
    dfd = dfd.then(function(){
        return scrape(url);
    }).then(function(results){
        console.log("results: "+results);
    });
});

Your problem lied in the $.when within each iteration. On the first iteration $.when created a new promise (unnecessary btw since scrape returns a promise), and then added a then to process results. On the next iteration, this original promise is not referenced and a new one is created for the next url (before the first scrape was completed!) and so on.

This solution keeps all of your async operations in the same $.Deferred chain, executing them sequentially (what you want).

You do get points for using the IIFE to freeze the value of i though!

Heres a jsFiddle

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.