Yetimwork Beyene
Yetimwork Beyene

Reputation: 2337

How to get data out of a deferred callback;

How do I get the returned data to work outside the deferred callback below?

             results.done(function(data)
             {
                   alert(data); // works
             });

             alert(data); // does not work but need it to work...

Upvotes: 0

Views: 67

Answers (2)

ryachza
ryachza

Reputation: 4540

You would need to store the data in a location accessible from the outer scope. If you store it in a global variable from inside the callback, it would be available; you just need to make sure, then, that the outer code is only executed after the asynchronous code completes.

Alternatively, you are able to call "done" multiple times (.done() returns the deferred object, so .done().done() or temp = .done(); temp.done() would work). If the result has already completed previously, the callback will execute immediately.

Upvotes: 1

Kevin B
Kevin B

Reputation: 95022

This will work, sometimes, but is a very bad idea.

var badIdea;
results.done(function(data) {
    alert(data);
    badIdea = data;
});

setTimeout(function(){
    alert(badIdea);
},10000);

Re-think your logic and do not try to get data outside of the done callback.

Upvotes: 4

Related Questions