'Link to a promise of async function inside of it

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?



Solution 1:[1]

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]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sam R