iorejson
iorejson copied to clipboard
Tutorial
Hey there,
I'm pretty new to Node.JS and had a difficult time understanding your example of how to use ReJSON.
I had to do hours of googling before I found something that worked for me. I first discovered that yield
statements only work inside of generator
functions. That was easy enough to find out. Of course afterwards I also read about Promises
. However, I had a very difficult time finding out how to get your Promises
to resolve.
I ended up finding someone who had this code that lets me pass in a generator
function, and it resolves all your promises returned in your yield
statements.
I'm unsure if there is a better way, but for now it is what I am doing.
reference: https://developers.google.com/web/fundamentals/getting-started/primers/promises
Wrapper code:
function spawn(generatorFunc) {
function continuer(verb, arg) {
var result;
try {
result = generator[verb](arg);
} catch (err) {
return Promise.reject(err);
}
if (result.done) {
return result.value;
} else {
return Promise.resolve(result.value).then(onFulfilled, onRejected);
}
}
var generator = generatorFunc();
var onFulfilled = continuer.bind(continuer, "next");
var onRejected = continuer.bind(continuer, "throw");
return onFulfilled();
}
Example code:
spawn(function* example(){
try{
var instance = new Rejson();
yield instance.connect();
yield instance.set('foo', '.', {
bar: {
hello: 'world'
}
});
value = yield instance.get('foo', '.');
}
catch(e){
console.log(e);
}
console.log(value);
});
Thanks for the feedback! I agree that generator is a bit confusing and the language itself is moving away from it as well (with the whole async/await
).
Technically, everything just returns a promise, so you can yield
it or you can just do the good old promise way:
var instance = new Rejson();
instance.connect().then(function() {
instance.set('foo', '.', {
bar: {
hello: 'world'
}
}).then(function() {
instance.get('foo', '.').then(function(value) {
console.log(value);
});
});
});
I totally agree with tylo. Thank you evan for the code above, it helped me as I was unfamiliar with the yield keyword. Maybe add a note on the README?
Unhandled rejection ReplyError: WRONGTYPE Operation against a key holding the wrong kind of value
at JavascriptReplyParser.returnError (/home/gurpreet/projects/pcm-edge/node_modules/iorejson/node_modules/ioredis/lib/redis/parser.js:25:25)
at JavascriptReplyParser.run (/home/gurpreet/projects/pcm-edge/node_modules/iorejson/node_modules/redis-parser/lib/javascript.js:135:18)
at JavascriptReplyParser.execute (/home/gurpreet/projects/pcm-edge/node_modules/iorejson/node_modules/redis-parser/lib/javascript.js:112:10)
at Socket.