I have a piece of code that submits a GET request to another part of my website in a function.
function getStatus(ID) {
$.get('/api/'+ID+'/info', function(statusCallback) {
return statusCallback;
});
}
console.log(getStatus(ID));
What I would expect this code to return and then log would be the information that I need.
What I actually get in console log is
undefined
What can I do to get the actual result?
You're doing async operation. In your case using callback. If you want to print statusCallback, you have to console.log it like Christos mentioned.
Also
console.log(getStatusId())
will return undefined because it's default value returned from the function that has no explicit return. Your function has no return statement, it's only calling some async method.
Btw, try promises instead of callbacks if you can ;)
With ES7 you can use async await
async function getStatus(ID) {
$.get('/api/'+ID+'/info', function(statusCallback) {
// This is executed in the future, but await knows how to deal with it
return statusCallback;
});
}
console.log(await getStatus(ID));
They are a good practice to get started with, because the code gets a lot easier to read.
You need to change your functions as below:
function getStatus(ID) {
$.get('/api/'+ID+'/info', function(statusCallback) {
console.log(statusCallback);
});
}
The function you pass as the second parameter of your get call is called success callback. It will be called, once the get request that is issued on each call of the getStatus function completes successfully. Only then you have access to what the server returned and you can fairly easy access it as above.
Update
If you want to return the data that server sends you have to declare first a variable
function getDataById(ID){
function callback(data){
return data;
}
$.get('/api/'+ID+'/info', function(data) {
return callback(data);
});
}
I am trying to pass a callback to a function, but keep getting the error,
Uncaught TypeError: callback is not a function.
loadContacts: function () {
var pageNumber = this.state.pageNumber,
pageSize = this.state.pageSize;
BasketService.getContacts(pageNumber, pageSize, function(contacts){
contacts = this.convertPropertyNames(contacts);
this.setState({
contacts: contacts
});
}.bind(this));
},
// trying to pass function callback here
listenerForRemoveContact: function(data){
BasketService.removePerson(data.id, this.loadContacts());
},
this.loadContacts() calls loadContacts and passes its return value to removePerson.
loadContacts doesn't have a return statement, so that value is undefined.
You are trying to use undefined as if it were a function.
If you want to pass loadContacts as the callback function, then don't call it: Remove the ().
Note that this will change the value of this inside the function, so you should also use bind() to maintain the context.
BasketService.removePerson(data.id, this.loadContacts);
^ you probably want to pass in the function object, not the result of calling the function
passing in
this.loadContacts()
will pass in the value which loadContacts returns (in this case it isn't returning anything)
Your code this.loadContacts() calls the function loadContacts and passes its return value to removePerson as argument.
loadContacts doesn't return anything, so the return value of that function is undefined.
If you want to pass loadContacts as the callback function, then don't invoke it just remove the invoking () from it.
Just pass like this
removePerson(data.id, this.loadContacts);
That's it.
I have this block of codes in my controller..
controller('ChallengeCtrl',function($scope,$http){
$scope.challenged = [];
$scope.checkVideo = function (video) {
var response;
console.log(url);
return $http.get(url).success(function(data) {
return data;
}).error(function(data){
return data;
});
}
$scope.challengeMe = function() {
$scope.checkVideo($scope.selectedVideo).then(function(data){
$scope.challenged = data.data;
console.log($scope.challenged); //working
});
}
$scope.printChallenge = function() {
console.log($scope.challenged); //not working, returns [] null
}
});
I assigned the value of $scope.challenged when i call challengeMe() function and I tried to console out the values inside $scope.challenged array on my printChallenge() function, but it returns to be null.
Assuming that you are calling challengeMe() and printChallenge() on page load, the problem is happening because challengeMe() has a async function call which populates data in $scope.challenged. While that async call is in progress you are executing your function ie printChallenge() with no time delay and since the call is not yet complete in challengeMe(), so $scope.challenged is not populated with any data.
To solve this problem you can either add a $timeoutor you can log your value the way you have done it in challengeMe()
Since ChallengeMe() is an async function, you need a timer function before you call PrintChallenge() method so that you wait until the data populates (Which is a wrong way to do as generally we don't know after how much time we would be having the data populated) OR may be you can have a WHILE loop just after the ChallengeMe() call and just before the PrintChallenge()Call. In the WHILE loop you can check whether $scope.challenged is not NULL.
The console message inside the .then inside the ChallengeMe() method works because .then executes only after the AJAX call has finished. But by this time the execution must have moved further to the PrintChallenge() method without waiting for the Data and thus the console message inside the PrintChallenge() callhas nothing.
I have the functions below:
(Normally I get the variable msg by doing some query on a XML Object)
function getMsg(callback) {
var msg = "test";
callback(msg);
}
function msgDone() {
var message = null;
getMsg(function(msg) {
message = msg;
});
return message; //Why is message undefined here?
}
My problem is that I get an undefined on message. I have tested the function getMsg(), and it returns the right value.
How will I make the msgDone to return the message that I get from callback? So that it doesn't return undefined?
Thanks
Why is message undefined here?
It won't be, in the code in the question, but my guess is that the real getMsg is an asynchronous operation. That is, when you call it, it starts the process of getting the message but that process completes later, not right away. (For instance, a typical ajax call is like this.)
In that case, the reason message is undefined in the location you marked is that the callback hasn't been called yet, so nothing has ever assigned to message. You can't return the result of an asynchronous call from a function; instead, you have to provide a callback mechanism of your own (simple callbacks, or promises, or similar). E.g.:
function getMsg(callback) {
// Do something asynchronous...
// It's done, call the callback
callback(/*...the data retrieved asynchronously...*/);
}
function msgDone(callback) {
getMsg(function(msg) {
// Presumably you do more processing here...
// ...and then call the callback
callback(msg);
});
}
Then, instead of:
var msg = msgDone();
doSomethingWith(msg);
doSomethingElseWith(msg);
you do:
msgDone(function(msg) {
doSomethingWith(msg);
doSomethingElseWith(msg);
});
I am having a hard time understanding how the callback() function is used in the following code block.
How are we using callback() as a function, in the function body, when function callback() has not been defined?
What are the repercussions of passing true / false as parameters into the callback function below?
I appreciate any clarification, thanks in advance!
socket.on('new user', function(data, callback){
if (nicknames.indexOf(data) != -1){
callback(false);
} else{
callback(true);
socket.nickname = data;
nicknames.push(socket.nickname);
updateUserList();
}
});
When you pass a function as an argument, it is known as a callback function, and when you return a value through this callback function, the value is a parameter of the passed function.
function myFunction(val, callback){
if(val == 1){
callback(true);
}else{
callback(false);
}
}
myFunction(0,
//the true or false are passed from callback()
//is getting here as bool
// the anonymous function below defines the functionality of the callback
function (bool){
if(bool){
alert("do stuff for when value is true");
}else {
//this condition is satisfied as 0 passed
alert("do stuff for when value is false");
}
});
Basically, callbacks() are used for asynchronous concepts. It is invoked on a particular event.
myFunction is also callback function. For example, it occurs on a click event.
document.body.addEventListener('click', myFunction);
It means, first assign the action to other function, and don't think about this. The action will be performed when the condition is met.
I agree with you, the code in the snippet is very unclear.
The answers you got are great, however none refers to the actual use of callback in your code, and I would like to reference that specifically.
First, I will answer your question, and then I will elaborate on the complexity of it.
The answer
turns out socket.io are doing something very cool which is not the standard I know..
socket.io are passing the callback from the front-end to the backend!
So to answer your question what is this callback function - you have to look at your frontend code.
Look for code that looks like this
socket.emit('new user', data, function( booleanParameter ){
// what are you doing with booleanParameter here?
});
I assume that in your case true/false values are meant to pass back to the frontend if new user was added (true) or not (false)..
Or perhaps if the nickname is already in use or not so that the frontend can show an error string if it is..
Basically, #SumanBogati was right in his answer, but I felt it was lacking the step of finding the callback in the front-end due to socket.io's special treatment.
Further Suggestion To make your code clearer
Change name of parameter data to nickname
Add comments - why are you placing nickname on socket?
add documentation
Use jsdocs to explain what the callback is doing
/**
#callback NewUserCallback
#param {boolean} booleanParameter does something..
**/
and then on the function itself
/**
#parameter {string} nickname
#parameter {NewUserCallback} callback
**/
The complexity
Usually, in nodejs, a callback expects the first argument to be an error, so reading your code, it says
socket.on('new user', function(data, callback){
if (nicknames.indexOf(data) != -1){
///// THERE IS NO ERROR
callback(false);
}else{
///// THERE IS AN ERROR
callback(true);
/// do more stuff after the error
socket.nickname = data;
nicknames.push(socket.nickname);
updateUserList();
}
});
Not the pattern you'd expect, is it? I guess this is why you asked the question.
Still the question remains what socket.io's callback means, right? Perhaps their callback does not expect an error as first argument.
I have never used socket.io, and I was unable to find a documentation to clarify this. So I had to download their chat example and debug it ==> and so the answer I gave, they are passing the function from the frontend to the backend.
Socket.io should definitely stress this point in large font in their documentation under a title named "How does socket.io handle callbacks?" or "How does our callbacks work?".
Great question! Learned a lot from it!
I'll try to simplify with a "concrete" example (I hope).
Let's say I have a function that "calculates" the current day and I'll call that function each time I would need the current day ("Don't call us, we'll call you" or whatever).
var getCurrentDay = function (callback) {
var currDate = new Date();
callback(currDate, 'err');
});
};
getCurrentDay(function (returnDay) {
logger.info('Today is: ' + returnDay); });
A callback function, is a function that is passed to another function (let’s call this other function “otherFunction”) as a parameter, and the callback function is called (or executed) inside the otherFunction.
Here is my simple example for callback function
// callback add
function add(a, b){
console.log(a+b);
}
// Main function
function getInput(cb) {
c = 5+5;
d = 6+6;
if (typeof cb === 'function') {
cb(c, d);
}
}
getInput(add)
For detailed explanation refer the this link
Without thinking too much, see the following example.
In the following example, I just call the print function from the add function.
function print( ans ){
console.log(ans) ; // 7
}
function add(a, b){
print(a+b) ;
}
add(2,5);
What if I use the print function as a parameter? Without using print function from global scope I just pass the print function as an argument.
function print( ans ){
console.log(ans) ; // 7
}
function add(a, b, callback){ // here callback = print
callback(a+b) ;
}
add(2,5,print); // print function as a parameter
Generally, JavaScript allows function as a parameter.
So any function that is passed as an argument is called a callback function.
I think now callback is understandable to you.
Callback function mean call after another:)
doHomeWork('math',alertMsg);
Above line said 1. call doHomeWork and then call 2. alertMsg, that's it.:)
function doHomeWork(subject,callback){
console.info("study: "+subject);
callback();
}
alertMsg = function(){
console.info("alert");
}
doHomeWork('math',alertMsg);
Output:
study: math
alert
A callback is any function that is called by another function using parameter
Here a query for you Suppose that Consider how programmers normally write to a file:
- `fileObject = open(file)` //now that we have to wait for the file to open, after that we can write to this file*
- fileObject.write("We are writing to the file.") // but i want to write , not wait
This case - where callbacks are helpful:
//we can pass **writeToFile()** (a callback function) to the open file function
- fileObject = open(file, writeToFile)
//execution continues flowing -- we do not wait for the file to be opened
//once the file is opened we can write to it, but while we wait we can do other things
Function inside a function is called a callback function. Or let me say that the inside function which is present inside the parent function is called the callback function.
If you want to complete a task2 after task1. Then you can make task2 as the callback and this will run asyncronously
Here is one example where the usage of callback function is easy to understand.
A login function which performs user login with the server asynchronously.
Due to asynchronous call , we need to get the result of login once the date receives from the server.
const axios = require('axios');
function login(loginData,callbackSuccess,callBackFailure) {
axios
.post("/api/login",loginData)
.then((response) => {
callbackSuccess(response);
})
.catch((error) => {
callBackFailure(error);
});
}
function callbackSuccess(data) {
console.log("Login response :",data);
}
function callBackFailure(error) {
console.log("Login failed :",error);
}
let userData = {
username : "test",
password : "abcd123"
}
login(userData,callbackSuccess,callBackFailure);