S
S
Spawner2017-08-18 22:11:58
JavaScript
Spawner, 2017-08-18 22:11:58

How to return a value from a callback?

I have a function inside a function that I pass another function to, it looks like this:

function user_params(id, param) {
  vk('users.get', {user_ids: id, fields: param}, function(error, response){
    if (error) {
      console.log(error);
    }
    return  response[0][param];
  });
};

I need to make sure that when this function is called, result[param] is returned to me.
I've been sitting with this for over an hour now, tried different ways, I'm sure the answer is on the surface

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Sergey Sokolov, 2017-08-18
@Spawner

The function user_params()will execute immediately and return null. And the answer from VK will be received sometime later and will fall into the nested function.
As an option, pass the function as the third parameter, which will be called later and into which the VK response will be passed:

function user_params(id, param, callback) {
  vk('users.get', {user_ids: id, fields: param}, function(error, response){
    if (error) {
      console.log(error);
    } else callback(response[0][param]);
  });
};

R
Ramil, 2017-08-18
@rshaibakov

Use promises :

function user_params(id, param) {
 return new Promise((resolve, reject) => {
    vk('users.get', {user_ids: id, fields: param}, function(error, response){
      if (error) {
        reject(error);
      }
      resolve(response[0][param]);
    });
  });
}

user_params(123, {}).then(res => {
  // ваши действия
}).catch(error => {
 console.error(error);
});

About async / await, I think I will not bother you))

M
maxfox, 2017-08-19
@maxfox

You just need to understand that the callback will be executed later, which is why you cannot return a value from the function. Just write the inner function separately, give it a name and do what you need in it. And pass it to vk(). You do not need to return anything, write code that will work with the received value right in this function.
And then you will deal with promises.

N
Negwereth, 2017-08-18
@Negwereth

The answer is to read about asynchrony.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question