Abel
Abel

Reputation: 355

Node JS Bluebird nested loops promise

I'm using bluebird in NodeJS. I want to do a nested loop. Something like this:

for (var i = 0; i < array.length; i++) {
   for (var j = 0; j < array.length; j++) {
        if (i !== j) {
            // do some stuff
        }
   }
}

How can I promisify this loop with bluebird?

I see some similar question here How to use promise bluebird in nested for loop? or here in node.js, how to use bluebird promise with a for-loop

But that does not clarify my doubt. I would like some explanation besides the code, since I do not really understand what I'm doing.

Thanks in advance!

Upvotes: 3

Views: 530

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276596

Sure, you're using Node, you have coroutines, use them:

function myWork = Promise.coroutine(function*() {
   for (var i = 0; i < array.length; i++) {
     for (var j = 0; j < array.length; j++) {
       if (i !== j) {
           // do some stuff
           // this can be async calls, for example
           yield thisReturnsAPromise(i, j); // call some async function
       }
     }
  }
});

To handle errors you can use regular try/catch. To call it you do doWork() with also returns a promise which you can then or catch.

The issue is that until ES2015 and generators, you had issues with returning async values and using them with regular flow control structures. In old Node, you'd have to use Promise.each on the array nested in a Promise.each returned and return the inner promise in that:

Promise.each(array, function(i) {
    return Promise.each(array, function(j) {
        return thisReturnAPromise(i, j); 
    });
});

Coroutines simplify this and yield back control to the promise pump that takes care of that.

Upvotes: 4

Related Questions