简体   繁体   English

从将按顺序执行的Promise数组中创建一个jQuery Promise

[英]Create a jquery promise from an array of promises to be executed sequentially

Does jquery have support for forming promises from an array of promises (or functions) to be executed in sequence? jQuery是否支持从将按顺序执行的诺言(或函数)数组中形成诺言? For example, 例如,

lets suppose I have this function defined 让我们假设我定义了这个功能

function wait(/*args*/){
    var complete = $.Deferred();
    var args = arguments;
    setTimeout(function(){
        console.log(args);
        //arguments are applied to show that the functionality should
        //pass arguments between promises in sequence.
        complete.resolve.apply(null,args);
    }, 1000);
    return complete.promise();
}

I could easily chain these together to form a new promise like so: 我可以轻松地将它们链接在一起以形成新的承诺,如下所示:

var sequencePromise = wait("first")
.then(wait.bind(null,"second"))
.then(wait.bind(null,"third"));

However i regularly have a long series of promises to sequence, or perhaps they are variable lists i am composing, so I am looking for a way to easily do something like: 但是我经常有很长的承诺序列,或者它们可能是我正在编写的变量列表,所以我正在寻找一种轻松完成类似任务的方法:

var sequence = [
    wait("first"),
    wait.bind(null,"second"),
    wait.bind(null,"third")];

var sequencePromise = $.whenInSeq(sequence)

preferably, I'm looking for a solution that isn't a large dependency (it'd be ideal if I just missed something within the jquery api). 最好是,我正在寻找一个没有很大依赖性的解决方案(如果我只是错过了jQuery API中的某些东西,那将是理想的选择)。 Wanted to confirm something doesn't exist before I roll my own. 想在我自己动手之前确认不存在的东西。

try this (untested): 试试这个(未试用):

var sequence = [
    wait("first"),
    wait.bind(null,"second"),
    wait.bind(null,"third")];

var s = sequence[0];
for (var i = 1; i < sequence.length; i++) {
  s = s.then(sequence[i]);
}
s.done(function () {alert('done!')})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM