Usually, I write code like this:
//definition
exports.getReply = function * (msg){
//...
return reply;
}
//usage
var msg = yield getReply (\'hello\'
Generators are functions with a .next() for getting the yield'ed values or you can yield a generator function to let it know it doesn't need to "wait" upon encountering a yield statement for a .next to be called (reply.getReply().next(fn))
Your second piece of code is almost correct:
class Reply{
*getReply (msg){
//...
return reply;
}
*otherFun(){
this.getReply(); //`this` seem to have no access to `getReply`
}
}
var Reply = new Reply();
Reply.getReply(); //out of class,how can I get access to `getReply`?
First of all, please use const or let when working in ES6 and only use the uppercase variant for classes.
You are trying to overwrite the class Reply statement with the var Reply = statement, which is not possible since the Identifier 'Reply' is already declared.
The answer you are looking for is as followed:
Just like you are doing in the first example, you should yield the generator functions, so your could should look like this:
class Reply{
*getReply (msg){
// yield something here, otherwise you should use a normal function
return reply;
}
*otherFun(){
const reply = yield this.getReply(); // yield the generator so it does what it needs to and doesn't wait for the .next() to be called on it
return `${reply} within class ${this.constructor.name}`;
}
}
const reply = new Reply();
const answer = yield reply.getReply('foo');
// getReply is a generator function, so it needs a `yield` or `.next()` to run beyond the first `yield` in the function