Having the console log getLastVideo(channel_id) makes it spit out undefined until I call it once more. I would like to wait for global.lastVideo, which the function returns, to not be undefined before returning it's value. Any help with this or an alternative solution is highly appreciated :^)
function getLastVideo(channel_id){
client.request.parseURL(`https://www.youtube.com/feeds/videos.xml?channel_id=${channel_id}`)
.then(data => {
global.lastVideo = data.items[0].link;
});
console.log('lastVideo: ' + global.lastVideo);
return global.lastVideo;
}
Fetching data from a remote address is an asynchronous action and your console.log
and return
statements will be executed before receiving the data.
You should make your function asynchronous and handle the logic to wait data before returning anything.
function getLastVideo(channel_id){
return client.request.parseURL(`https://www.youtube.com/feeds/videos.xml?channel_id=${channel_id}`)
.then(data => {
global.lastVideo = data.items[0].link;
console.log('lastVideo: ' + global.lastVideo);
return global.lastVideo;
});
}
Or you can use async/await
version
async function getLastVideo(channel_id){
const data = await client.request.parseURL(`https://www.youtube.com/feeds/videos.xml?channel_id=${channel_id}`);
global.lastVideo = data.items[0].link;
console.log('lastVideo: ' + global.lastVideo);
return global.lastVideo;
}