1

I am trying to set a variable within one promise method and access it in another, but not having much luck.

I have this code:

$.getJSON('some/file/')
.done(function(response) {
    var foo = response;
})
.always(function() {
    // How can I access 'foo' here?
});

So how can I access the foo variable in other promise methods?

Brett
  • 19,449
  • 54
  • 157
  • 290
  • 1
    You'll need to declare `foo` outside of `done()` – Tushar Sep 07 '15 at 08:10
  • This looks like a very bad idea. `foo` wouldn't be set if the promise failed, so your `always` callback would throw trying to use it. What do you actually want to do, what is your real problem that you need to solve? – Bergi Sep 07 '15 at 14:01

1 Answers1

2

It is all about the scope if you declare variable outside done() function then you can access it in always()

var foo;
$.getJSON('some/file/')
.done(function(response) {
    foo = response;
})
.always(function() {
    // How can I access 'foo' here?
    console.log(foo);
});

You may find this interesting as well. Also remember that always will be executed when ajax fails.

Community
  • 1
  • 1
Robert
  • 19,800
  • 5
  • 55
  • 85
  • Make sense, thanks very much. Yep, know about the `always` thing, that's the behaviour I want. :) – Brett Sep 07 '15 at 08:15
  • maybe done/fail methods is better approach – Robert Sep 07 '15 at 08:17
  • Nope, for the situation I am using the code for I don't want the code within the `always` block to rely on the outcome of the retrieval of the JSON file - it *always* has to be executed. – Brett Sep 07 '15 at 08:29