-1

I am trying to assign a value to a variable at the parent function level through some nested self-invoking functions. I am new to javascript coding and am having some trouble getting the value of the variable out of the nested function. Is the value being loaded asynchronously? Or is there another fix to this?

function searchA(keyword_string) {

                var video_id = '';
                var q = keyword_string;
                var request = gapi.client.youtube.search.list({
                        q: q, 
                        part: 'snippet',
                        maxResults: '1',
                        type: 'video',
                        order: 'relevance',
                        videoEmbeddable: 'true'
                });
                request.execute(function(response) {
                        var str = JSON.stringify(response.result);
                        var json = response.result;
                        video_id = json.items[0].id.videoId;
                        console.log(video_id); //THIS GIVES THE CORRECT ID
                });
                console.log(video_id); //THIS RETURNS AN EMPTY STRING 
        }
Adway Dhillon
  • 77
  • 1
  • 4
  • 16
  • The line returning the incorrect `video_id` is being executed BEFORE the line returning the correct one. Inspect the code a bit, and you'll immediately know why. – treecoder Jun 29 '17 at 00:48
  • The first line where it assigns video_id to an empty string? Yes, but am I not reassigning its value to json.items[0].id.videoId? The scope of that variable remains local to that function. How do I make it global to the entire parent function "searchA()" – Adway Dhillon Jun 29 '17 at 00:53
  • Scope isn't the issue here, it's the order of execution. – David L. Walsh Jun 29 '17 at 00:56

1 Answers1

0

Yes, the value is being loaded asynchronously.

I don't know the specifics of the Google API, but the first parameter of the request.execute method must be the callback function, which is executed only when the response arrives.

That way, the last console.log(video_id) is executed before video_id = json.items[0].id.videoId.

tiagodws
  • 1,345
  • 13
  • 20