Anthony Chung Anthony Chung - 1 year ago 72
Javascript Question

generators + promises to parallelize N number of items

the challenge:

  1. We want to make N parallel ajax requests for an item's children.

  2. Upon returning, we want to process them in sequential order (1...N)

  3. We do NOT want to wait for all promises to return, but we want to process them IN ORDER as they come back.

For example:

Even if 2,3,5 come back before 1, we should hold onto the results of 2,3,5, and upon 1's return, process 1,2,3 in order (and wait for 4 to come back before 5)

Tools: Q + ES6 generators

Create array of N-1 length with placeholder variables

EG when N = 3:

let [N1,N2,N3] = yield [ Promise1, Promise2, Promise3 ]

//process items sequentially:

However, populating an array of empty variables doesn't seem to work of course because the reference doesn't know where to find the var declaration

for(var i = 0; i< 3; i++) {
res.push("some empty var")

Given the constraints of sticking to the tools provided, how could we parallelize calls, but process their returns sequentially?

Answer Source

You can do that by waiting for the next promise inside the loop:

const promises = […]; // or created programmatically
for (const promise of promises) {
    const result = yield promise; // await them sequentially
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download