[英]How to sequentially run promises with Q in Javascript?
I am having a hard time running promises sequentially. 我很难按顺序执行诺言。
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() should sequentially output ["Once", "upon", "a", "time"] but instead they are being output immediately for some reason. OnceUponATime()应该顺序输出[“ Once”,“ upon”,“ a”,“ time”],但是由于某种原因,它们会立即输出。
jsFiddle here: http://jsfiddle.net/6Du42/2/ jsFiddle在这里: http : //jsfiddle.net/6Du42/2/
Any idea what I am doing wrong? 知道我在做什么错吗?
but instead they are being output immediately for some reason. 但由于某种原因,它们却立即被输出。
You are calling them already here: 您已经在这里打电话给他们:
promiseFuncs.push(getDelayedString(str));
// ^^^^^
You would need to push function(){ return getDelayedString(str); }
您需要推送function(){ return getDelayedString(str); }
function(){ return getDelayedString(str); }
. function(){ return getDelayedString(str); }
。 Btw, instead of using pushing to an array in an each
loop you rather should use map
. 顺便说一句,与其在each
循环中使用推入数组,不如使用map
。 And actually you don't really need that anyway but can reduce
over the strings
array directly: 实际上,您实际上并不需要,但是可以直接reduce
strings
数组:
function onceUponATime() {
var strings = ["Once", "upon", "a", "time"];
return strings.reduce(function (soFar, s) {
return soFar.then(function() {
return getDelayedString(s);
});
}, Q());
}
Oh, and don't use document.write
. 哦, 不要使用document.write
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.