我很难按顺序运行承诺。
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() 应该顺序输出 ["Once", "on", "a", "time"] 但由于某种原因它们会立即输出。
jsFiddle在这里:http: //jsfiddle.net/6Du42/2/
知道我做错了什么吗?