Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 436
Abel Avatar asked May 24 '26 01:05

Abel


1 Answers

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.

like image 100
Benjamin Gruenbaum Avatar answered May 26 '26 15:05

Benjamin Gruenbaum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!