2009-06-17 78 views
0

我試圖用doh.Deferred編寫測試,將檢查以下事件調用序列:是否有可能測試異步函數序列與DOH

  1. 登錄與用戶A(異步)
  2. 註銷(同步)
  3. 登錄與用戶A(異步)

第二回調函數的返回值是另一個doh.Deferred對象。我的印象是,d的回調鏈將等待d2,但它不會。測試在d2.callback被調用之前完成。

我在哪裏錯了?

有沒有人知道更好的方式來測試這種行爲?

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; 
} 

回答

0

This works。 d2的範圍是問題。

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; 
} 
相關問題