2013-08-22 11 views
8

Mam twardy czas pracy obietnic sekwencyjnie.Jak sekwencyjnie uruchamiać obietnice z Q w JavaScript?

var getDelayedString = function(string) { 
    var deferred = Q.defer(); 

    setTimeout(function() { 
     document.write(string+" "); 
     deferred.resolve(); 
    }, 500); 

    return deferred.promise; 
}; 

var onceUponATime = function() { 
    var strings = ["Once", "upon", "a", "time"]; 

    var promiseFuncs = []; 

    strings.forEach(function(str) { 
     promiseFuncs.push(getDelayedString(str)); 
    }); 

    //return promiseFuncs.reduce(Q.when, Q()); 
    return promiseFuncs.reduce(function (soFar, f) { 
     return soFar.then(f); 
    }, Q());  
}; 

getDelayedString("Hello") 
.then(function() { 
    return getDelayedString("world!") 
}) 
.then(function() { 
    return onceUponATime(); 
}) 
.then(function() { 
    return getDelayedString("there was a guy and then he fell.") 
}) 
.then(function() { 
    return getDelayedString("The End!") 
}) 

onceUponATime() powinny kolejno wyjście [ "Po", "nad", "a", "czas"], lecz zamiast tego są wysyłane bezpośrednio z jakiegoś powodu.

jsFiddle tutaj: http://jsfiddle.net/6Du42/2/

Każdy pomysł co robię źle?

Odpowiedz

15

, ale zamiast tego są one natychmiast generowane z jakiegoś powodu.

Jesteś nazywając je już tutaj:

promiseFuncs.push(getDelayedString(str)); 
//        ^^^^^ 

Trzeba by pchnąć function(){ return getDelayedString(str); }. Btw, zamiast korzystania pchania do tablicy w pętli each raczej powinno użyć map. I rzeczywiście tak naprawdę nie trzeba, że ​​w każdym razie, ale może reduce nad strings tablica bezpośrednio:

function onceUponATime() { 
    var strings = ["Once", "upon", "a", "time"]; 

    return strings.reduce(function (soFar, s) { 
     return soFar.then(function() { 
      return getDelayedString(s); 
     }); 
    }, Q());  
} 

Aha, i don't use document.write.

+0

Dzięki za odpowiedź i dodatkowe podpowiedzi! – Nick

+1

tak, to musi być funkcją * * fabrycznie do pracy, inaczej wykonuje się natychmiast. – FlavorScape

Powiązane problemy