如何在 Javascript 中使用 Q 顺序运行承诺? [英] 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() 应该按顺序输出 ["Once", "upon", "a", "time"] 但由于某些原因它们会立即输出.
onceUponATime() should sequentially output ["Once", "upon", "a", "time"] but instead they are being output immediately for some reason.
jsFiddle 在这里:http://jsfiddle.net/6Du42/2/
jsFiddle here: http://jsfiddle.net/6Du42/2/
知道我做错了什么吗?
推荐答案
但由于某种原因,它们被立即输出.
but instead they are being output immediately for some reason.
你已经在这里给他们打电话了:
You are calling them already here:
promiseFuncs.push(getDelayedString(str));
// ^^^^^
你需要推送 function(){ return getDelayedString(str);}
.顺便说一句,与其在 each
循环中使用推送到数组,不如使用 map
.实际上你并不真正需要它,但可以直接在 strings
数组上reduce
:
You would need to push function(){ return getDelayedString(str); }
. Btw, instead of using pushing to an array in an each
loop you rather should use map
. And actually you don't really need that anyway but can reduce
over the strings
array directly:
function onceUponATime() {
var strings = ["Once", "upon", "a", "time"];
return strings.reduce(function (soFar, s) {
return soFar.then(function() {
return getDelayedString(s);
});
}, Q());
}
哦,还有 不要使用 document.write
.
这篇关于如何在 Javascript 中使用 Q 顺序运行承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!