0

I notice that when I make str a global variable, instead of making it return from a function like I do in the search function below, it works as it should. However, when I try and return it, it returns undefined. How do I resolve this? I do not want to use globals as I want the search function to be atomicized.

function search(query) {
    var str;
    // Use the JavaScript client library to create a search.list() API call.
    var request = gapi.client.youtube.search.list({part:'snippet',q:query});

    request.execute(function(response) {
    str = JSON.stringify(response.result);
    str = JSON.parse(str);
        //console.log(str);
    });
    return str;
}

1 Answer 1

1

I believe your making an async call... That means your function will return str before the callback has been executed!

That is why your getting undefined:

var str; // Undefined!
...
return str; // Returns before your callback executes...

The problem with synchronous calls is you might freeze the client if your waiting for a response and it never arrives!

One way would be to call another method called something like 'gotSearchResults(results)' when your callback executes.

Another dirty way I do not recommend at all is to start a loop, keep running it until str is defined and you got a result.

The best way would properly be to make a callback yourself

function search(query, callback) {
    var str;
    // Use the JavaScript client library to create a search.list() API call.
    var request = gapi.client.youtube.search.list({part:'snippet',q:query});

    request.execute(function(response) {
        str = JSON.stringify(response.result);
        str = JSON.parse(str);
        //console.log(str);

        callback(str); // Execute your callback with the string as argument!
    });
}

search('some query', function(result) {
   console.log(result);
});

This is the best way, and I believe the most correct way to achieve what you want!

Hope it helps :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.