guptron guptron - 1 year ago 91
Javascript Question

With a Javascript Promise, how to close over variables local to the parent scope in a `then`?

If I have code like this:

Blog.add = function(account) {
const url = '';
response =;

response.then(function(response) {
// There is no access to account or url here.

When I break in the
closure, I see that
is bound to the global object which seems strange to me. Shouldn't it be bound to the
function?. I've tried arrow functions with the same result. I'm definitely not understanding what's going on here...

Answer Source

You have several questions here. I'll attempt to answer them:

  1. You should be able to close over account inside the Promise callback without any issues. If you're not seeing it when you hit a breakpoint, it's simply because it's not actually used in your code yet (the debugger won't close over it dynamically, you have to have code that uses it for it to be captured).

  2. this will be bound however the Promise implementation is implemented.

  3. In your case, we're not seeing enough of the code to know what this could be. It all depends on how Blog.add is actually being called. If lexical binding via => is still giving you the global namespace, then there's an "issue" with your call.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download