0

I have the following code:

function addToPlaylist ({params}) {
  debugger
  return new Promise((resolve, reject) => {
    getPlaylistItems().then((items) => {
      if (!items.content) { items.content = [] }
      debugger
      resolve()
    })
  })
}

Nevermind what it does, it's just a work in progress and it doesn't really work yet, hence why I'm putting debugger calls in there.

My question: why is params available at the first breakpoint, but not at the second? I get an 'Uncaught ReferenceError: params is not defined'.

I tried doing params = params at the beginning because I thought that was a trick which would work, but it doesn't. I tried const _params = params as well, and it wasn't available inside the then(items) => scope either.

What's the deal? I thought Javascript had lexical scoping.

This is happening from a "background script" in a Chrome Extension.

chrome_debugger_1

chrome_debugger_2

max pleaner
  • 26,189
  • 9
  • 66
  • 118
  • 1
    Looks like the old _"promise constructor anti-pattern"_ since `getPlaylistItems()` appears to return a promise already – Phil Nov 28 '19 at 03:12
  • Can't see anything wrong with `params` though. It should definitely be available. Since you aren't actually using `params` anywhere though, what is telling you it's not there? – Phil Nov 28 '19 at 03:14
  • @Phil I do appreciate you pointing that out, but keep in mind this method is only half written. I understand the anti-pattern you're referring to. – max pleaner Nov 28 '19 at 03:14
  • 1
    I can't reproduce this. If I log `params` in the callback it works fine. It would be more helpful if you had code that actually reproduced the problem. – Mark Nov 28 '19 at 03:14
  • @maxpleaner I don't see a `params` anywhere in that code, aside from the parameter to `addToPlaylist`. How are you seeing that it's not available? Through the debugger? – Matt U Nov 28 '19 at 03:17
  • In Firefox, I do get an error for `params` when within the `Promise` ~ _"Error: variable `params' has been optimized out"_ so this is just debugger optimisation I guess – Phil Nov 28 '19 at 03:18
  • 1
    I don't think that it holds on to the closure since you don't have any reference to params in the callback. It probably just gets GC'd. – Jared Smith Nov 28 '19 at 03:20
  • Can you create a simplified version of the code that we can plop into a JS environment and test it? – DemiImp Nov 28 '19 at 03:24
  • Thank you all. Simply writing `params = params` in the inner scope fixed it. – max pleaner Nov 28 '19 at 03:26

0 Answers0