我很难按顺序运行 promise。
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"] 但由于某种原因它们被立即输出。
jsFiddle 在这里:http://jsfiddle.net/6Du42/2/
知道我做错了什么吗?
最佳答案
but instead they are being output immediately for some reason.
你已经在这里给他们打电话了:
promiseFuncs.push(getDelayedString(str));
// ^^^^^
您需要推送 function(){ return getDelayedString(str); }
。顺便说一句,与其在 each
循环中使用推送到数组,不如使用 map
.实际上你并不真的需要它,但可以直接在 strings
数组上reduce
:
function onceUponATime() {
var strings = ["Once", "upon", "a", "time"];
return strings.reduce(function (soFar, s) {
return soFar.then(function() {
return getDelayedString(s);
});
}, Q());
}
哦,还有don't use document.write
.
关于javascript - 如何在 Javascript 中使用 Q 顺序运行 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18386753/