UPDATE: I am currently researching and trying to implement this using a Promise. It isn't working just yet but I believe I am getting close. If anyone has any input about a Promise is a better way to go than settimeout I would appreciate your feedback.
I am currently using the feedsub module that reads an rss feed and sends the data back to my app.
Currently my code looks like:
var reader = new FeedSub('http://pathtosite/atom.xml', {
emitOnStart: true
});
reader.read(function(err,items){
atomXMLposts = items;
console.log(atomXMLposts);
});
The reader.read
accepts a callback function that runs when it receives the items argument.
the console.log(atomXMLposts)
logs the items in an array, which is what I want. But...
When I run this block of code right after:
atomXMLposts.forEach(function(post){
// console.log(post["published"]);
var now = moment(post["published"]);
console.log(now);
})
I receive an error saying TypeError: Cannot call method 'forEach' of undefined
I believe this is a result of of the function running before atomXMLposts
is assigned the values. So I wrapped a setTimeout around this code block.
setTimeout(function(){
// if(atomXMLposts)
atomXMLposts.forEach(function(post){
// console.log(post["published"]);
var now = moment(post["published"]);
console.log(now);
})
}, 2500);
This returns values but I personally feel using setTimeout is not a good practice. The 2500 ms I added is an arbitrary number I guesstimated
. What would be a better way of handling this? Is there a better way? I am trying to search for a better alternative, when I search using setTimeout to wait for parameters
or something to that nature, I am not receiving anything that is useful.