Forgive me if this is a commonly asked question, I'm new to JavaScript.
I'm attempting to use the library "video-url-link" from npmjs.
The Readme provides the following example:
videoUrlLink.twitter.getInfo('https://twitter.com/{@}/status/{ID}', {}, (error, info) => {
if (error) {
console.error(error);
} else {
console.log(info.full_text);
console.log(info.variants);
}
});
This works fine, but what are my options if I want the "info" object to persist outside of the scope of the callback?
I've tried declaring a variable outside the getInfo call, then setting it inside the callback, which I didn't expect to work - and it doesn't work(!)
What I have is:
const get_twitter_video_info = (video_url) => {
var nfo = {};
try
{
videoUrlLink.twitter.getInfo(
video_url,
{},
(error, video_info) => {
if (error !== undefined)
console.log(error);
if (video_info !== undefined)
{
nfo = JSON.parse(JSON.stringify(video_info));
}
}
);
}
catch(err)
{
console.log (err);
throw(err);
}
return nfo;
}
thanks in advance.
You are attempting return nfo before the callback is even called. In the code, get_twitter_video_info will return an empty object and then getInfo will return the response and the callback will be called (where you are using nfo and video_info). You can either utilise nfo in the callback itself and process further or you can use async/await.