2016-05-26 101 views
1

我正在尝试所有人都如此兴奋的承诺。他们应该减少代码的复杂性,这是我还没有注意到的一个功能。使用蓝鸟承诺做N次

在我的情况下,我有一个函数返回Promise。该函数通过ADB在Android设备上调用按键向上或向下事件。我这样称呼它:

press(B_KEY, 3000, client, device) 
    .then(function(result) {console.log("Key press done.");}); 

我想执行这个动作(也称press)函数)的顺序几次。我可以手动做到这一点:

press(B_KEY, 3000, client, device) 
    .then(function(result) {return press(B_KEY, 3000, client, device);}) 
    .then(function(result) {return press(B_KEY, 3000, client, device);}) 
    .then(function(result) {return press(B_KEY, 3000, client, device);}) 
    // ad nauseam 

我想有类似for循环的东西。我试图想到伪代码来向你展示,但我拥有的任何想法都非常难看。

如何使用Promises中的所有功能进行循环?

+2

可能的复制蓝鸟承诺](http://stackoverflow.com/questions/29375100/while-loop-using-bluebird-promises) – mdickin

+0

@mdickin我读过这个问题和其他几个。只是FYI,而lop和for循环是不同的东西。 –

+0

'for'循环只是while循环的子类。 – mdickin

回答

0

为了达到你的目的,你可以使用mapSeries()对一个空数组迭代n次:

return Promise.mapSeries(new Array(4), function() { 
     return press(B_KEY, 3000, client, device); 
    }); 

有关mapSeries更多信息()参见[While循环使用的reference