Pergunta

Eu estou tentando usar doh.Deferred para escrever um teste que irá verificar a seguinte sequência de eventos:

  1. login com o usuário A (assíncrono)
  2. log out (síncrono)
  3. login com o usuário A (assíncrono)

O valor de retorno da segunda função de retorno é outro objeto doh.Deferred. Fiquei com a impressão de que a cadeia de retorno de chamada de d irá esperar por d2, mas isso não acontece. Os acabamentos teste antes d2.callback nunca é chamado.

Para onde estou indo errado aqui?

Alguém sabe de uma maneira melhor para mim para testar este comportamento?

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;
}
Foi útil?

Solução

Isso funciona. O escopo de D2 era o problema.

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;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top