On Tue, May 15, 2012 at 10:48 AM, Brent Lingle <[email protected]> wrote:
> Hello, thanks in advance for your help.
>
> I get the concept of callbacks, and I can see how to use them with the
> node api. But, I'm having trouble fitting them into my own code.
> Below is a sample of what I'm talking about.
>
> I'm writing a small api for myself, so that I can use information from
> tumblr on my own site. Here is the line from my app.js file. This
> particular method retrieves the avatar url from tumblr.
>
> //This line would return the host name, I can't figure out how to add
> a callback into this.
> tumblr.avatar('#some host name', 64);
>
> The next piece of code is out of my tumblr.js file that I created.
>
> exports.avatar = function(hostName, size) {
You want your avatar function to be asynchronous, so one way to
achieve that is to pass in a callback that will be invoked when you
function has the URL it wants to return. You could change the line
above to:
exports.avatar = function(hostName, size, cb) {
> var obj;
>
> if (typeof size === Number) size = 64;
>
> //create an options for http.get()
> var options = {
> host: 'api.tumblr.com',
> port: 80,
> path: '/v2/blog/' + hostName +
> '.tumblr.com/avatar/' + size
> };
>
> //retrieve the url of the avatar
> var req = http.get(options, function(res) {
> var data = '';
>
> res.on('data', function(chunk) {
> data += chunk;
> });
>
> res.on('end', function(err) {
> obj = JSON.parse(data);
> obj = obj.response.avatar_url;
At this point you have the URL you want to return. You could do this:
cb(null, obj);
Passing null as the first argument indicates that no error occurred.
The callback function passed in should have "err" as its first
parameter and check for errors.
Your call to JSON.parse(data) will throw an error if data isn't valid
JSON. You should do something like this:
try {
obj = JSON.parse(data);
cb(null, obj.response.avatar_url);
} catch (e) {
cb(e);
}
> });
> });
> };
>
>
> I already have the call back within the http.get() method, but I can't
> figure out where to put a call back into my avatar function, to return
> the URL of the avatar back to the app.js file.
>
> So my question is how would I go about adding a callback to this
> function, so that I don't block node?
--
R. Mark Volkmann
Object Computing, Inc.
--
Job Board: http://jobs.nodejs.org/
Posting guidelines:
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
You received this message because you are subscribed to the Google
Groups "nodejs" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/nodejs?hl=en?hl=en