Ok, no problem, I thought. I tried putting the feed directly in my server.js file. There was a simple problem - I don't have the blog data because feed-read has made an asynchronous call to gather the feed information leaving me with nothing.
Once I understood the problem I started searching for solutions. What generally comes up are yet more helpful libraries to help you 'deal with' the async 'problem'.
I am sure there are more complicated problems which may merit a complex library but I happen to know that this is something that JavaScript is great at. JQuery introduced the idea of a promise in version 1.5 and this is basically the same problem, with a similar solution. So the answer?
In my case chain callbacks. Yes, if you are using a function from an abstracted module, pass in a function which will then pass a function etc... When the function at the bottom of the chain passes us some data back we will be ready!! Use an API call to do this perhaps so we can give our users a spinner while they are waiting.
var blogReader = {
GetMostRecentBlog : function(callback) {
feed('http://bloglocation.com/feeds', function(articles) {
var mostRecentBlogPost = articles[0];
var blog = {
Title: mostRecentBlogPost.title,
Content: mostRecentBlogPost.content
};
callback(blog);
});
};
module.exports = blogReader;
You then can use it like :
blogReader.GetMostRecentBlog(function(blog) {
//use Blog object here for display
});
I found this exact pattern in Mixu's Node book chapter 7 - http://book.mixu.net/node/ch7.html.
He also talks about two other useful patterns to deal with asynchronous calls which may be useful on larger scale projects - Parallel and Limited Parallel patterns.As always, the code for my solution can be found on github.
No comments:
Post a Comment