The .load
function is not only enclosing variables into a new scope, it's also running asynchronously. What this means is that any code declared immediately after your call to load will actually run before the code within your load callback is run (which will only run after the rss feed is loaded).
What this means is any code that is dependent on the return should therefore be inside the callback function. Like so:
var Feed = require('rss-to-json');
Feed.load('https://learnstartup.net/feed/', function(err, rss){
console.log(rss);
console.log(rss.items[0].title);
});
However, you can see how this nesting can cause readiability issues if you have many nested callback functions. So, depending on your runtime, you can take advantage of the ES6 syntax which introduces the concept of async/await
which basically says, "This function is asnychnrous, so wait until it finishes before proceeding." Like so:
var Feed = require('rss-to-json');
(async function() {
var myfeed = await new Promise((resolve, reject) => {
Feed.load('https://learnstartup.net/feed/', function(err, rss){
if (err) { return reject(err) }
resolve(rss)
});
});
console.log(myfeed);
console.log(myfeed.items[0].title);
})();
I should point out, the later option is a little more complicated because the convenient await
keyword can only be used inside an async
function so I had to wrap the code in an IIFE. Happy to provide more clarity if needed, but if you're new my recommenation is to start with option 1 and consider reading more about these other concepts:
async await
Callbacks vs async await