I try to make a little script with node.js (v6.5.0). The first part of this script displays a word randomly found in a list. Then it uses the word (as the key) the display its value (the translation). The script requires the node-redis module. The problem I get seems related to the asynchronous nature of the functions. Is it because the first function is asynchronous that I can't reuse the argument in the nested one? I'm stucked and some directions would be really appreciated.
Here's a snippet of the code...
var redis = require('redis');
var fs = require('fs');
var client = redis.createClient();
client.on('connect', function() {
});
client.randomkey(function (err, word) {
console.log('The question is: ' + word);
client.get('word', function(err, reply) {
if (err) {
console.log(err);
}
//otherwise show the value of this key.
});
});
client.quit();
... and this the error message I get when launching the command node drill.js
The question is: chicken
{ AbortError: Stream connection ended and command aborted. It might have been processed.
at RedisClient.flush_and_error (...thesaurus/node_modules/redis/index.js:350:23)
at RedisClient.connection_gone (...thesaurus/node_modules/redis/index.js:585:14)
at Socket.<anonymous>
(...thesaurus/node_modules/redis/index.js:282:14)
at Socket.g (events.js:286:16)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at TCP._handle.close [as _onclose] (net.js:493:12) code: 'NR_CLOSED', command: 'GET', args: [ 'word' ] }
You should call the inner function with the variable, not a string. It will not work like that.
client.randomkey(function (err, word) {
console.log('The question is: ' + word);
client.get(word, function(err, reply) {
if (err) {
console.log(err);
} else {
console.log(reply);
}
// put quiting of the client here NOT at the end of your document
client.quit();
});
});
And then you didn't output the result of the second query.
EDIT: And of course you can't close the connection the way you do, as you would close the connection before the inner function is finished.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With