0

Asynchronous JS hurts my brain... ;)

1  const aoSpecialInstrumentTSLMgrs = [];
2  await asInstruments.forEach(async sInstrument => {
3      const oInstrument = await CInstrument.fpoGet(sInstrument);
4      const oSpecialInstrument = new CSpecialInstrument(this, oInstrument, oTimeframe);
5      const oSpecialInstrumentTSLMgr = new CSpecialInstrumentTSLMgr(oSpecialInstrument);
6      await oSpecialInstrumentTSLMgr.fInit();
7      aoSpecialInstrumentTSLMgrs.push(oSpecialInstrumentTSLMgr);
8  });
9  // then more code here.

I need this to run as if it were synchronous. Hence the asyncs/awaits, of course. By the time I reach line 9, I need the aoSpecialInstrumentTSLMgrs array to be populated with what's supposed to be pushed into it in line 8...

But that's not happening.

When I step through it in my debugger -- even with a breakpoint on every line of the above code in case I'm pressing the wrong buttons as I step through or something -- it goes to line 3, then steps into the CInstr….fpoGet() as expected. That's an async function by necessity. It steps through that function, also as expected. But then when it steps out of that function it goes straight to line 9 and skips all of lines 4 - 8.

I believe it's because it's asynchronous code inside a loop -- I've probably got some asyncs/awaits in the wrong places?

How do I get it to run the above lines in the order they would if everything was synchronous -- ie. run lines 4-7 (as many times as there are asInstruments of course) before it hits line 9?

And why doesn't the above work?

Thanks!

(PS. This is forEach instead of map because it's actually populating a few arrays inside the forEach not just one, but I've simplified it down to just one, for the question. So even if array.map is part of a solution here that might fail me. I believe I need it to be forEach. In case that makes any difference.)

DavidT
  • 655
  • 7
  • 19
  • Did you try `for await ... of` ? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of – ZeroWorks Jan 22 '23 at 12:35
  • [`forEach`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) returns `undefined`. `undefined` cannot be awaited. Use [`map`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map) and [`Promise.all`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) or a similar method. – Sebastian Simon Jan 22 '23 at 12:36

0 Answers0