The problem
I am making a music player for friends. One person is the host, only they play the music, and others just paste a Youtube link, and then it gets sent through a Node.Js server.
I am using embedded Youtube videos to play the music. I am getting the Youtube video id from the links, and just adding them onto the embed link.
I want to make a playlist feature, so that people can see what videos are next. I have multiple Youtube ids, so getting the titles should be easy as that, because tools were already made for this scenario.
These tools are pretty simple: you have the Youtube id, and maybe you need a Youtube API key as well, but then you can console.log()
the data.
But when I want to display the data other than logging it onto the console, it just breaks. The application won't wait until the gather ends. It just returns undefined
.
I've tried server-side, and client-side versions too, both failed. Javascript never waits.
And I don't want to use PHP, I want to stay with Js/NodeJs/jQuery.
What I've tried
Node.js
The get-youtube-title npm package;
const titles = [];
getYoutubeTitle(videoid, api-key, function(err, title) {
console.log(title); // this only logs data when collected.
titles.push(title); // this pushes too early, and does not wait until the data is collected.
}
console.log(titles[0]);
This next code is from this post
console.log(get_title(video-id));
async function get_title(video-id) {
// this also doesn't work. returns undefined.
await getYoutubeTitle(video-id, api-key, (e, t) => {
return this.title = t
});
}
When using your own API key, it gets the titles accurately. What I've learned when researching for this, is that Node.js is asynchronous (this is my first node.js project, don't judge me), so it kind of makes sense.
I've tried a couple more packages, but those also failed.
- ytdl-core from this post
- a fork of the original get-youtube-title npm-package, get-youtube-title-await
- always using this setup:
const titles = [];
// geting title with some npm-package and pushing data in titles;
console.log(titles[0]); // undefined
jQuery
That is when I've switched to the client. I am using socket.io, and I've found out that this is also async both on client and server. I've tried this answer on stackoverflow, and same issue.
Even though Javascript should be single-threaded, so it should wait, right?
I am using google's cdn.
I don't really want to use jQuery, but if only this version works, jQuery answers are appreciated.
Conclusion
Console.log()-ing always works! It always waits until the data is collected!
I just want to change a div's innerText, and it returns undefined.