0

How can I pass msg variable in foreach and get its updated value after foreach finishes... Here is some pieces of code which I am trying to workout...

class Handlers {
    .....
    .....
      async addFunc(item, logger) {
        const msg = [];
        [1,2,3,4,5].forEach(async (id) => {
          const result = await this.Request.req(`/items/${id}`, logger, 'GET');
          const result2 = await this.repository.get(result.name);
           .....
           ...
           ...
           if (result.a === result2.b){
             msg.push('I am test');
           }
        });
      if (msg.length > 0) {
        return true;
      }
      return false;
      }
    .....
    ....
    }
Developer
  • 25,073
  • 20
  • 81
  • 128
  • 1
    Don't pass an `async` function into something that won't handle the fact it returns a promise (like `forEach`). Either use a `for-of` loop (if you want to do these things in series) or use `map` and use `Promise.all` on the result to wait for all the promises to resolve: `const msg = []; await Promise.all([1, 2, 3, 4, 5].map(async (id) => { /*...*/ }); return msg.length > 0;` But do you really want to do **all** of these just to see if **any** of them had a matching result? – T.J. Crowder Apr 07 '19 at 16:43
  • When I used for of, I get following [eslint] iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations. [no-restricted-syntax] [eslint] Unexpected `await` inside a loop. [no-await-in-loop] – Developer Apr 07 '19 at 21:15

0 Answers0