-1

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?

Christos
  • 53,228
  • 8
  • 76
  • 108
Techius
  • 9
  • 5

3 Answers3

0

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);
   });
}
Christos
  • 53,228
  • 8
  • 76
  • 108
  • Using that would mean that I wouldn't be able to use any of the information from the request. It would only log it. Thanks anyway – Techius Sep 09 '18 at 13:37
  • From your post, I understood that you just want to log to the console the response your get. What do you want to achieve ? – Christos Sep 09 '18 at 13:38
  • I'd like to return the data so that I can treat it like a string for example – Techius Sep 09 '18 at 13:39
0

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 ;)

Papi
  • 741
  • 6
  • 8
0

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.

Pavlo
  • 1,157
  • 7
  • 13
  • 1
    This doesn't work, await doesn't know how to deal with it, it's not a promise – Luca Kiebel Sep 09 '18 at 14:09
  • Yup, it will only work if we'll return a promise from `getStatus`. async/await is only (or not only) syntactic sugar on top of promises. – Papi Sep 09 '18 at 18:22