Search code examples
javascriptarraysnode.jsbluebird

Node: Process a 2D array of promises


I have a 2D array (2 X n) of promises and I want first to process all the promises in Row 1 and then all the promises in Row 2.

In other words, I want to chain one group of promises after another group of promises completes its execution.

How can I achieve this?

I tried the following but it doesn't work. Any ideas?

 Promise.resolve()
    .then(createPromises)//generates topPromises= [ [p1, p2, p3], [p4,p5,p6]]
    .then(function(topPromises){
      Promise.all(topPromises[0])
      .then(Promise.all[topPromises[1])
    })

Solution

  • You can pull this off using a little bit of pseudo-recursion.

    Essentially, you have a function which completes one group of promises. Once it completes, you call that same function again but with the next group.

    let promiseCount = 1;
    function create() {
      let n = promiseCount++;
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log(n);
          resolve();
        }, 500 * n);
      });
    }
    
    let groups = [
      [create(), create(), create()],
      [create(), create(), create()],
      [create(), create(), create()]
    ];
    
    (function runGroup(i) {
      if (i < groups.length) {
        Promise.all(groups[i])
          .then(() => {
            console.log('Group', i + 1, 'complete');
            runGroup(i + 1);
          });
      }
    })(0);