views:

121

answers:

1

I am trying to use doh.Deferred to write a test that will check the following sequence of events:

  1. login with user A (asynchronous)
  2. log out (synchronous)
  3. login with user A (asynchronous)

The return value of the second callback function is another doh.Deferred object. I was under the impression that the callback chain of d will wait for d2 but it does not. The test finishes before d2.callback is ever called.

Where am I going wrong here?

Does anyone know of a better way for me to test this behavior?

function test() {
    var d = new doh.Deferred();

    d.addCallback(function() {  
     Comm.logout(); /* synchronus */
     try { 
      // check with doh.t and doh.is
      return true;
     } catch (e) {
      d.errback(e);
     }
    });

    d.addCallback(function() {
     var d2 = new dojo.Deferred();
     /* asynchronus - third parameter is a callback */
     Comm.login('alex', 'asdf', function(result, msg) {
       try {
        // check with doh.t and doh.is
        d2.callback(true);
       } catch (e) {
        d2.errback(e);
       }     
      });
     return d2; // returning doh.Defferred -- expect d to wait for d2.callback
    });  

    /* asynchronus - third parameter is a callback */
    Comm.login('larry', '123', function (result, msg) {
     try {
      // check with doh.t and doh.is 
      d.callback(true);
     } catch (e) {
      d.errback(e);
     }
    }); 

    return d;
}
A: 

This works. The scope of d2 was the problem.

function test() {
    var d = new doh.Deferred();
    var d2 = new doh.Deferred();

    d.addCallback(function() {  
        Comm.logout(); /* synchronus */
        try {   
                // check with doh.t and doh.is
                return true;
        } catch (e) {
                d.errback(e);
        }
    });

    d.addCallback(function() {
        /* asynchronus - third parameter is a callback */
        Comm.login('alex', 'asdf', function(result, msg) {
                        try {
                                // check with doh.t and doh.is
                                d2.callback(true);
                        } catch (e) {
                                d2.errback(e);
                        }                                       
                });
        return d2; // returning doh.Deferred -- waits for d2.callback
    });         

    /* asynchronus - third parameter is a callback */
    Comm.login('larry', '123', function (result, msg) {
        try {
                // check with doh.t and doh.is 
                d.callback(true);
        } catch (e) {
                d.errback(e);
        }
    }); 

    return d;
}
Lawrence Barsanti