Do something N times using Bluebird Promises

2019-07-15 05:58发布

问题:

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