如何在Javascript中用Q順序運(yùn)行promises?我很難順序運(yùn)行promises。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()應(yīng)該按順序輸出[“Once”,“on”,“a”,“time”],但是由于某種原因它們會立即輸出。jsFiddle這里:http://jsfiddle.net/6Du42/2/知道我做錯了什么嗎?
如何在Javascript中用Q順序運(yùn)行promises?
有只小跳蛙
2019-08-23 09:49:02