Answer the question
In order to leave comments, you need to log in
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];
});
};
Answer the question
In order to leave comments, you need to log in
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]);
});
};
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);
});
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question