1

I want to process batches of data in series, like shown in the code below. In this context a single batch is simply an array containing values. So the function sendInBatches() expects an array of arrays as input.

async sendInBatches(batches) {
    for (const batch of batches) {
       const promises = batch.map(x => asyncMethod(x));
       await Promise.all(promises);
    }
}

Below is the code for asyncMethod(). Note that the asyncMethod() doesnt actually do anything with the provided argument yet. It simply returns a Promise that resolves after 1 second.

asyncMethod(batch){
    return new Promise((resolve) => {
        setTimeout(
            () => {
                console.log('x');
                resolve();
            }
            , 1000,
        );
    });

}

I try running the code like this:

sendInBatches([[1,2,3],[4,5,6],[7,8,9]]).then(console.log('done'));

This provides the output:

done
x
x
x

While I want it to return:

x
x
x
done

I cant figure out whats going wrong here, do you guys have an idea?

Elias
  • 432
  • 6
  • 17
  • 6
    You are passing `console.log("done")` into the `.then` directly, not as part of a function. So it will evaluate it immediately. Instead, try `.then(() => console.log("done"))` and you should get the result you want. – CRice Feb 05 '18 at 19:43
  • You're right! Thanks for the quick response. Cant believe I overlooked something so simple. – Elias Feb 05 '18 at 19:46

1 Answers1

2

Solved:

You are passing console.log("done") into the .then directly, not as part of a function. So it will evaluate it immediately. Instead, try .then(() => console.log("done")) and you should get the result you want.

see comment of CRice

Peter
  • 1,742
  • 15
  • 26
Elias
  • 432
  • 6
  • 17