0

I tried to return value from callback to a variable but it doesn't work For example:

var events;

function getEvents(callback) {
  $.ajax({
    // ...
    success: function(data) {
      callback(data);           
    }
 });
 // return data;
}

function eventSucess(data) {
  events = data;
};

getEvents(eventSucess);
console.log(events);

// Finally the value from events = nothing but If I tap  events in the browser console  I will have the correct value.

I want to have the value in my variable events.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Your `getEvents` doesn’t currently accept any parameter. Add `callback` as a parameter there. – Sebastian Simon Jun 22 '18 at 10:18
  • You cannot return anything from an asynchronous operation; it's like trying to eat a pizza before it's been delivered. You're already using the callback pattern properly to set the value of `events` in the `eventSuccess` function, you just need to put all logic which depends on `events` *within* that function (or *call it* from that function) – Rory McCrossan Jun 22 '18 at 10:20
  • yeap I forgot that but I have the same problem. – Sara Quispe Jun 22 '18 at 10:20
  • `console.log(events);` must be moved to inside the "eventSuccess" function...otherwise it will execute before that function has fired, and thus the events object will appear to be empty. – ADyson Jun 22 '18 at 12:54
  • @ADyson I did that but how I do for put the data's value into a varaiable who is outside of my function? – Sara Quispe Jun 22 '18 at 13:18
  • you can do it by setting a global variable, but you cannot expect to _use_ that variable until the ajax and the resulting callback has finished. You must refactor your code to take account of that. Making use of the fact that $.ajax returns a Promise would make sense. If you don't know about Promises (and jQuery Deferred objects), now would be a great time to take a tutorial. – ADyson Jun 22 '18 at 13:23

0 Answers0