-2

I have a API call and I expected to write response to friends variable.

getFriends = function() {
  return VK.Api.call('friends.get', {}, function(response) {
    if (response.response)
      response.response;
  });
};

var friends = getFriends();
console.log(friends)  // undefined;

In my previous question one guy told me that I can fix it with callback function and close my question. I implement a callback but again I can't get a response.

var getFriends = function(callbackFn) {
  return VK.Api.call('friends.get', {}, function(response) {
    if (response.response) {
      callbackFn(response.response);
    }
  });
};

var friends = getFriends(function(list) { return list; });

How I can write response.response to variable for a lot of next manipulations?

Community
  • 1
  • 1
Bob Napkin
  • 566
  • 6
  • 15
  • You **must** read the answer of the question we link to. You **can't** just return the value from your function which gets it with an asynchronous call. – Denys Séguret May 30 '15 at 08:45
  • @DenysSéguret I read what I need a callback function. You **must** read the my question. I write about it in second paragraph – Bob Napkin May 30 '15 at 08:47
  • you must read the whole answer, not just one sentence. There is no way to code in JavaScript without understanding this fundamental problem. – Denys Séguret May 30 '15 at 08:51
  • @DenysSéguret but is it good way to close question without helpful answer? – Bob Napkin May 30 '15 at 08:58
  • 1
    This question is asked many times a day. We built very complete answers like the one I linked you to so that you can read them instead of the bad incomplete ones like the one below. – Denys Séguret May 30 '15 at 09:04

1 Answers1

-2

It's actually much simpler

var friends = null;
VK.Api.call('friends.get', {}, function(response) {
    if (response.response) {
      friends = response.response;

      console.log(friends);
    }
}
php_nub_qq
  • 15,199
  • 21
  • 74
  • 144