-3

I have a function called 'getAuthor' and inside there's an ajax events running (refer below)

function getAuthor(id){
    $.get('http://www.connectnigeria.com/articles/wp-json/wp/v2/users/74',function(e){
        var author = e.name;
        console.log(author);
        return author;
    });
}

try to run from the console, you'll see it returns "undefined" while console.log display the expected response from the ajax call.

Any, ideas help please?

Juliver Galleto
  • 8,831
  • 27
  • 86
  • 164
  • see this : [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – vibhor1997a Dec 19 '17 at 04:46
  • You are trying to return the author inside the anonymous function. Not from getAuthor function – Deepak Kumar T P Dec 19 '17 at 04:51

1 Answers1

0

Unless there is a explicit return from a function , it will always return undefined.

In console it is undefined because the function getAuthor is not returning anything. Not to be confused with the return from $.get.

The console.log statement is inside this asynchronous function. To get a return from the function getAuthor try this

function getAuthor(id){
    return $.get('http://www.connectnigeria.com/articles/wp-json/wp/v2/users/74',function(e){
        var author = e.name;
        console.log(author);
        return author;
    });
}
brk
  • 48,835
  • 10
  • 56
  • 78