Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Change variable in function and keep it javascript?

Change variable in function and keep it javascript?

Problem

How can I write this so that Lfmuser keeps the change made in the Function called by UserModel.find()? I'd really rather not have to move a very VERY large section of code into each block if I can avoid it.

var np_handler = function (act) {
  var lfmuser = '';
  if (act.params.length === 0) {
    UserModel.find({ nick: act.nick }, function (err, data) {
      if (!data) {
        lfmuser = act.nick;
      } else {
        lfmuser = data.lastfm;
      }
    });
  } else {
    UserModel.find({ nick: act.params[0] }, function (err, data) {
      if (!data) {
        lfmuser = act.params[0];
      } else {
        lfmuser = data.lastfm;
      }
    });
  }
};

Ended up not mattering in this situation, I just moved the rest of the code (where I was using lfmuser) to it's own function np(lfm, act){ } and passed the right value when I called it. Async can be a pain :/

Problem courtesy of: Rob

Solution

The easiest solution would be to move it outside of your np_handler function. Note that subsequent calls to the function will then overwrite its value, however.

Solution courtesy of: rjz

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Change variable in function and keep it javascript?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×