0

I use this function

        await getTestData(entry).then(res=> {
            for(let i = 0; i < res.length; i++){
                //console.log(res[0].data)
                console.log("line");
            }

        }).catch(error => {
            console.log("MongoGetError");
        });
  console.log("end");

The result is

  1. line
  2. end

Now I have to put this into a .forEach() loop. I tried:

    testcases.forEach(async function(entry,index) {


        await getTestData(entry).then(res=> {
            for(let i = 0; i < res.length; i++){
                //console.log(res[0].data)
                console.log("line");
            }

        }).catch(error => {
            console.log("MongoGetError");
        });

    });

    console.log("End");

But the result is:

  1. End
  2. line
  3. line

What is my fault to get finally

  1. line
  2. line
  3. end
Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
ingo
  • 776
  • 1
  • 10
  • 25
  • You could try `map` instead of `forEach`, then wrap the entire `testcases.forEach(`…`)` in a `Promise.all(`…`).then(() => console.log("End"))`. Currently, your `console.log("End")` is executed first, because there’s nothing that waits for the asynchronous `forEach` to finish. Soon, you might try [`allSettled`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled#Browser_compatibility) rather than `all`, which wouldn’t fail if one of the iterations fails. – Sebastian Simon Oct 22 '19 at 12:21

1 Answers1

0

Note - you have do the iteration in a method which return something like map(); forEach() doesn't return anything
step 1 - put the map() inside promise.all() method
step 2 - you have to hold the promise.all() by await or .then() or by any other child process

Shubham Tiwari
  • 1,761
  • 11
  • 19