guptron guptron - 5 months ago 10
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 = 'http://fetchdata.com';
response = HTTP.post(url);

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


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

Answer

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.

Comments