使用Bluebird Promises做N次 [英] Do something N times using Bluebird Promises
问题描述
我正在尝试每个人都感到非常兴奋的Promises.应该减少它们的代码复杂性,这是我尚未观察到的功能.
I am trying the Promises everyone is so excited about. They're are supposed to reduce code complexity which is a feature I've yet to observe.
就我而言,我有一个返回Promise的函数.该函数通过ADB在Android设备上调用向上或向下键事件.我这样称呼它:
In my case, I have a function that returns Promise. The function invokes key up or down event on Android device over ADB. I call it like this:
press(B_KEY, 3000, client, device)
.then(function(result) {console.log("Key press done.");});
我想按顺序执行几次此动作(调用press
).我可以手动执行此操作:
I would like to perform this action (call the press
) function) several times in sequence. I can do this manually:
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
的循环.我试图想到伪代码来向您展示,但是我的任何想法都很难看.
I would like to have something like for
loop. I tried to think of pseudocode to show you, but any ideas I have are really ugly.
如何使用Promises中的所有功能进行for循环?
How to make for loop with all it's features in Promises?
推荐答案
要实现您的目标,您可以使用mapSeries()在空数组上迭代n次:
To achieve your goal you could use mapSeries() to iterate n times over an empty array:
return Promise.mapSeries(new Array(4), function() {
return press(B_KEY, 3000, client, device);
});
有关mapSeries()的更多信息,请参见参考
For more info about mapSeries() see the reference
这篇关于使用Bluebird Promises做N次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!