Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

outside of client's scope? #60

Closed
NHQ opened this issue Feb 2, 2011 · 3 comments
Closed

outside of client's scope? #60

NHQ opened this issue Feb 2, 2011 · 3 comments
Labels

Comments

@NHQ
Copy link

NHQ commented Feb 2, 2011

Hi there. I'm not sure if I have run up against a limitation of this module, or of my skill. I can't seem to do anything with the return of a query outside of the optional function. The only way I can do anything to the data, is to put everything inside that function, i.e. passing the data as locals (res.render). Can you please set me straight?

For instance, I unable to attach the reply to a variable.

var data = client.get("test", function(err, reply){})

Similarly, I am unable to do this:

var data;
client.get("test", function(err, reply){
data = reply.toString()
})  // data undefined 

Only this works, but it is not the ideal construction:

client.get("tester", function(err, data) {
res.render('index', {
    locals: {
      title: '',
      body: data
   }
     })
});
@aeosynth
Copy link

aeosynth commented Feb 3, 2011

That's what you have to do with async functions in general, not just redis. There's a whole crop of modules (search for Flow Control / Async Goodies) dedicated to making async easier.

@mranney
Copy link
Contributor

mranney commented Feb 3, 2011

Your second example should work though, but you are probably getting confused about the order in which things run. Check out this program:

var client = require("redis").createClient();

client.set("some key", "some val");
var data;
client.get("some key", function (err, res) {
    data = res;
    console.log("Inside callback, data is: " + data);
});
console.log("Outside callback, data is: " + data);

This will output:

Outside callback, data is: undefined
Inside callback, data is: some val

Note that the "Outside callback" ran first. Since client.get() is a potentially blocking operation, the callback is noted, and control passes immediately (as far as you are concerned) to the next line in your program.

Note also that client.set() and client.get() are both operations that complete asynchronously, but they are guaranteed to complete in order. So you know that the get will not invoke the callback until the set is complete.

@NHQ
Copy link
Author

NHQ commented Feb 3, 2011

Ah-ha, thanks for that bit of tutorial.

This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants