loading...

re: Common Node.js mistakes in Lambda VIEW POST

TOP OF THREAD FULL DISCUSSION
re: const sleep = (ms) => new Promise(r => setTimeout(r, ms)); // from the linked post [1, 2, 3].forEach(async (num) => { await sleep(50); ...
 

Yeah, I see the same behaviour as you in Node 8, so it's possible the console.log issue is related to Node7.

But it wasn't the problem that I was hoping to highlight (my bad!), which is that it doesn't behave as you'd expect when you await sleep(50) inside an async function. It has stung me in the past where we had something along the lines of

xs.forEach(async (x) => {
  const result = await doSomething(x);
  // do something with results
})

doSomethingElseAfterAllResultsAreProcessed();

which fails because by the time doSomethingElseAfterAllResultsAreProcessed runs the results haven't actually been processed in the forEach. Once you understand the problem it's easy to see why it behaved that way, but it wasn't intuitive as the time of writing the code (which is why I actually made this mistake multiple times before I eventually "learnt the lesson").

code of conduct - report abuse