I
I
iDrugov2017-01-19 00:49:15
JavaScript
iDrugov, 2017-01-19 00:49:15

How to write response to global variable from VK API?

I have a clear problem with the scope, because I do not understand how to display the response in a global variable in order to use it further) I do not want to process data only inside the method function.
i = VK.api() - of course it doesn't work.

var i = 0;

VK.api('groups.getById', {group_id: 'live'}, function (r){
  i = r.response[0].id;
  return i;
});

alert(i); // например, не суть.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stalker_RED, 2017-01-19
@Stalker_RED

You have a problem with asynchrony.

var i = 0;

console.log(1, 'запрос отправляется')
VK.api('groups.getById', {group_id: 'live'}, function (r){
  i = r.response[0].id;
  console.log(4, i); // здесь сработает правильно, но только после ответа с сервера
  return i;
});

console.log(2, 'ответ на запрос еще не пришел, а вы уже пытаетесь использовать переменную i')
console.log(3, i); // выведет 0

UPD: about
i = VK.api() - of course it doesn't work.

You have return i;inside an anonymous function that is used as a callback parameter for VK.api()
What exactly returns VK.api() can be found in their source code or documentation. Maybe it doesn't return anything at all.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question