问题描述
我对使用 Promises 还很陌生,并且很难将我的头放在 jQuery deferreds 上.
I am fairly new to using Promises and have a hard time of wrapping my head around jQuery deferreds.
我目前拥有的是在某个点执行的一组函数:
What I currently have is an array of functions which I execute at a certain point:
while (queue.length) {
(queue.shift())();
}
问题在于,其中一些函数是异步的,但我需要它们一个接一个地运行.
The problem with this is, that some of those functions are asynchronous, but I need them to run one after another.
因此队列中的一些函数返回延迟(例如通过 jQuery.ajax()),而有些只是普通函数.我想知道是否可以按顺序 + 顺序执行它们(仅在前一个函数完成后才执行下一个函数).
So some of the functions in the queue return a deferred (e.g. via jQuery.ajax()) and some are just normal functions. I would like to know if how it would be possible to execute them in order + sequentially (executing the next function only when the previous one has finished).
我想也许 jQuery.when 会是我正在寻找的东西,但我不知道如何准确地找到它,我只是想出了这个:
I thought maybe jQuery.when would be what I am looking for, but I can't figure out how to it exactly, I came only up with this:
var deferred = jQuery.Deferred();
while (queue.length > 0) {
deferred.done().then(queue.shift());
}
推荐答案
非常精明,jQuery.when
正是您要寻找的.它接受一个 promise 或一个正常的 non-thenable 并返回一个超过该值的 promise.但是,由于您在这里有函数而不是值,因此这不是真正需要的,因为无论如何这是 .then
的行为.
Very astute, jQuery.when
is what you're looking for. It takes either a promise or a normal non-thenable and returns a promise over that value. However, since you have functions and not values here that isn't really required since this is the behavior of .then
anyway.
var queue = [syncFunction, syncFunc2, returnsPromiseAsync];
var d = $.Deferred().resolve();
while (queue.length > 0) {
d = d.then(queue.shift()); // you don't need the `.done`
}
(小提琴)
或者,您可以减少;
var res = queue.reduce(function(prev,cur){ // chain to res later to hook on done
return prev.then(cur);
}, $.Deferred().resolve());
如果你有更多的代码在这下面做事情,因为队列中的函数可能同步或异步运行(或者一些同步然后我们碰到一个异步的),为了避免混乱,你可能需要确保函数总是运行异步.您可以通过将 resolve
包装在 setTimeout
中的初始 Deferred
上来轻松做到这一点:
If you have more code doing things below this, since the functions in the queue may run synchronously or asynchronously (or some synchronous and then we hit an async one), to avoid chaos you may want to ensure that the functions always run asynchronously. You can easily do that by wrapping the resolve
on the initial Deferred
in a setTimeout
:
var p = $.Deferred();
var res = queue.reduce(function(prev,cur){ // chain to res later to hook on done
return prev.then(cur);
}, p);
setTimeout(p.resolve.bind(p), 0);
现在进程在超时发生之前不会启动,并且在此之后的任何代码肯定会在队列中的第一个函数之前运行.在我看来,这与 jQuery 承诺的语义不一致(因为 它们在同步与异步方面不一致回调),但您可能需要一致性.
Now the process won't start until the timeout occurs, and any code following this will definitely run before the first function from the queue does. In my view, that's inconsistent with the semantics of jQuery's promises (because they are inconsistent about sync vs. async callbacks), but you may want the consistency.
如果您需要知道过程何时完成,只需在 res
上使用 .then
处理程序:
If you need to know when the process completes, just use a .then
handler on res
:
res.then(function() {
// All functions have now completed
});
对于这些情况,这里有一个简单的包装函数,可以同时执行:
For those situations, here's a simple wrapper function that does both:
function clearQueue(q) {
var p = $.Deferred();
setTimeout(p.resolve.bind(p), 0);
return q.reduce(function(prev,cur){
return prev.then(cur);
}, p);
}
示例使用(fiddle):
clearQueue(queue).then(function() {
console.log("All done");
});
console.log("This runs before any queued function starts");
这篇关于jQuery:按顺序执行函数数组(延迟和非延迟)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!