3

Consider this simplified code

;(async () => {
  const a = [1, 2]
  const p = a.map(async (v, i) => {
    if (i === 0) {
      return await 1
    }
    return await p[i - 1]
  })
  console.log(await Promise.all(p))
})()

In V8 (Chrome/NodeJS) it rices an error "ReferenceError: p is not defined"

In firefox it just gives nothing

The question: is what is wrong with it?

Agat
  • 358
  • 2
  • 10

2 Answers2

4

I'm pretty sure you meant a[i-1]. The p variable is not yet initialised when the map callback is executed. Firefox may not yet implement the temporal dead zone because of backcompat concerns.

Your code might (should) work when you accessed p asynchronously, that is after having awaited something else:

const p = a.map(async (v, i) => {
  if (i === 0) {
    return await 1
  }
  await void 0; // delay until `p` is available
  return await p[i - 1]
})

However I would consider that to be horrible and confusing code. If you want to do something sequentially in an asynchronous function, use a standard loop:

for (const v of a)
  await 1;

and if you want to run some tasks in parallel, use Promise.all but make sure that they don't depend on each other.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • This is a simplified example, so actually await in the line before is what I need. Thank you – Agat Sep 04 '17 at 18:41
0
return await p[i - 1]

p is used inside the .map function and isn't available when it is called.

You probably mean:

return await a[i - 1]
Sam R
  • 696
  • 3
  • 7