Do something N times using Bluebird Promises

回眸只為那壹抹淺笑 提交于 2020-01-15 06:23:28

问题


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.

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.");});

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

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.

How to make for loop with all it's features in Promises?


回答1:


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);
    });

For more info about mapSeries() see the reference



来源:https://stackoverflow.com/questions/37463265/do-something-n-times-using-bluebird-promises

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!