如何按顺序执行承诺数组? [英] How can I execute array of promises in sequential order?

查看:145
本文介绍了如何按顺序执行承诺数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var promises = [promise1,promise2,...] ..,promiseN]; 

调用RSVP.all将并行执行它们:

  RSVP.all(promises).then(...); 

但是,如何按顺序运行?



我可以手动堆栈它们这样

  RSVP.resolve()
.then(promise1)
.then(promise2)
...
.then(promiseN)
.then(...);

但问题是承诺的数量各不相同,承诺数量是动态构建的。 >

解决方案

如果您已经在数组中存在,那么它们已经在执行。如果你有承诺,那么它已经执行了。这不是一个承诺的问题(IE他们不像C#任务在这方面与 .Start()方法)。 .all 不执行任何
它只是返回承诺。



如果你有一个数组的承诺返回功能:

  var tasks = [fn1,fn2,fn3 ...]; 

tasks.reduce(function(cur,next){
return cur.then(next);
},RSVP.resolve())然后(function()
//所有执行
});

或值:

  var idsToDelete = [1,2,3]; 

idsToDelete.reduce(function(cur,next){
return cur.then(function(){
return http.post(/ delete.php?id = + b $ b});
},RSVP.resolve())然后(function(){
//所有执行
});


I have an array of promises that need to run in sequential order.

var promises = [promise1, promise2, ..., promiseN];

Calling RSVP.all will execute them in parallel:

RSVP.all(promises).then(...); 

But, how can I run them in sequence?

I can manually stack them like this

RSVP.resolve()
    .then(promise1)
    .then(promise2)
    ...
    .then(promiseN)
    .then(...);

but the problem is that the number of promises varies and array of promises is built dynamically.

解决方案

If you already have them in an array then they are already executing. If you have a promise then it's already executing. This is not a concern of promises (I.E they are not like C# Tasks in that regard with .Start() method). .all doesn't execute anything it just returns a promise.

If you have an array of promise returning functions:

var tasks = [fn1, fn2, fn3...];

tasks.reduce(function(cur, next) {
    return cur.then(next);
}, RSVP.resolve()).then(function() {
    //all executed
});

Or values:

var idsToDelete = [1,2,3];

idsToDelete.reduce(function(cur, next) {
    return cur.then(function() {
        return http.post("/delete.php?id=" + next);
    });
}, RSVP.resolve()).then(function() {
    //all executed
});

这篇关于如何按顺序执行承诺数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆